Leetcode刷题笔记题解(C++):1971. 寻找图中是否存在路径

思路:

1.建立图集,二维数组,path[0]里面存放的就是与0相连的节点集合

2.用布尔数组来记录当前节点是否被访问过,深度优先会使用到

3.遍历从起点开始能直接到达的点(即与起点相邻的点),判断那个点是否已经走过,并进入递归继续遍历与那个点相邻的点,直到抵达终点。

class Solution {
public:
    bool visted[200000];//记录当前节点是否访问过
    bool validPath(int n, vector<vector<int>>& edges, int source, int destination) {
        vector<vector<int>>path(n);//保存图集,节点---节点相连的节点集合
        for(int i = 0;i <edges.size();i++){
            path[edges[i][0]].push_back(edges[i][1]);//建立图集
            path[edges[i][1]].push_back(edges[i][0]);
        }
        return dfs(path,source,destination);
    }
    bool dfs(vector<vector<int>>& path, int source, int destination){
        visted[source] = true;//记录当前节点已经被访问过了
        if(source == destination) return true;//如果source为目标节点了则返回真
        for(int i = 0;i < path[source].size();i++){
            //如果下一节点没有被访问过且深度优先搜索为真则返回真
            if(visted[path[source][i]] == false && dfs(path,path[source][i],destination)) return true;
        }
        return false;
    }
};

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-01-27 18:22:03       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-01-27 18:22:03       100 阅读
  3. 在Django里面运行非项目文件

    2024-01-27 18:22:03       82 阅读
  4. Python语言-面向对象

    2024-01-27 18:22:03       91 阅读

热门阅读

  1. 【无标题】OpenAi

    2024-01-27 18:22:03       50 阅读
  2. Docker 的基本概念和优势

    2024-01-27 18:22:03       59 阅读
  3. 第六章(原理篇) 微前端间的通信机制

    2024-01-27 18:22:03       55 阅读
  4. TCP三次握手-普通话版

    2024-01-27 18:22:03       44 阅读
  5. 处理器架构

    2024-01-27 18:22:03       53 阅读
  6. mysql5.7.19安装步骤

    2024-01-27 18:22:03       59 阅读
  7. 文档 OCR 识别优化为异步思路逻辑

    2024-01-27 18:22:03       44 阅读
  8. IDEA中pom中打包引入的jar包

    2024-01-27 18:22:03       66 阅读
  9. Chrome Devtools 调试指南

    2024-01-27 18:22:03       55 阅读