zoukankan      html  css  js  c++  java
  • 程序员面试金典 <Cracking the Coding Interview> 面试题 04.01. 节点间通路

    地址 https://leetcode-cn.com/problems/route-between-nodes-lcci/

    节点间通路。给定有向图,设计一个算法,找出两个节点之间是否存在一条路径。
    
    示例1:
     输入:n = 3, graph = [[0, 1], [0, 2], [1, 2], [1, 2]], start = 0, target = 2
     输出:true
    
    示例2:
     输入:n = 5, graph = [[0, 1], [0, 2], [0, 4], [0, 4], [0, 1], [1, 3], [1, 4], [1, 3], [2, 3], [3, 4]], start = 0, target = 4
     输出 true
    
    提示:
    节点数量n在[0, 1e5]范围内。
    节点编号大于等于 0 小于 n。
    图中可能存在自环和平行边。

    示例配图

    算法1
    (dfs)
    使用set数组记录图的结构

    //========================================

    从起点开始对图进行DFS

    class Solution {
    public:
        set<int> ss[100010];
        int vis[100010];
        bool dfs(int curr,int target)
        {
            bool ret=false;
            if(curr == target) return true;
    
            //标记当前点已经访问过
            vis[curr] = 1;
            for(auto& e:ss[curr]){
                if(vis[e] != 1){
                    ret = dfs(e,target);
                    if(ret) return ret;
                }      
            }
    
            return false;
        }
    
        bool findWhetherExistsPath(int n, vector<vector<int>>& graph, int start, int target) {
            for(int i =0; i < graph.size();i++){
                int a=graph[i][0]; int b = graph[i][1];
                ss[a].insert(b);
            }
            return dfs(start,target);
        }
    };
    作 者: itdef
    欢迎转帖 请保持文本完整并注明出处
    技术博客 http://www.cnblogs.com/itdef/
    B站算法视频题解
    https://space.bilibili.com/18508846
    qq 151435887
    gitee https://gitee.com/def/
    欢迎c c++ 算法爱好者 windows驱动爱好者 服务器程序员沟通交流
    如果觉得不错,欢迎点赞,你的鼓励就是我的动力
    阿里打赏 微信打赏
  • 相关阅读:
    SAR图像处理 MSTAR数据库利用问题
    python 获取系统环境变量 os.environ and os.putenv
    python 模块中的 __init__.py __main__.py
    pylint python2.7 安装记录
    Python--字典
    哈希表
    AC自动机模板
    平衡树(Splay)模板
    矩阵快速幂 模板
    非递归线段树
  • 原文地址:https://www.cnblogs.com/itdef/p/14470753.html
Copyright © 2011-2022 走看看