Directed Graph Loop detection and if not have, path to print all path.

这里总结针对一个并不一定所有点都连通的general directed graph, 去判断graph里面是否有loop存在, 收到启发是因为做了[LeetCode] 207 Course Schedule_Medium tag: BFS, DFS, 这个题实际上就是监测directed graph里面是否有loop存在. 我在网上看了比较经典的做法为DFS, 并且用三个set去标志not visited点,(0), 正在visiting的点(-1), 已经visited过的点(1), 我结合这个思路, 用dictionary去"模拟"这个的三个set, 分别用0, -1, 1 表示not visited, visiting, and visited.

1) Check whether have loop in directed graph

实际上就是找backedge, 如果判断edge是backedge呢, 就是说从node出发的指针指向了node自己或者它的祖先node, 那么表明是backedge, 同时也表明了有loop存在. 所以实际上就是用DFS去依次访问每个node, 如果node是1, 表明visited过了(并且从node出发的所有path都被visited过了), 就continue, 如果是-1, 表明visiting但是再次被visited, 所以直接返回False, 否则没有visited过, 将其标志为-1, visiting, 然后直到把所有从node出发的path的node都监测一遍没问题, 再将node tag为1, 表明visited过了, 并且返回continue. 直到所有的点都没返回False, 那么返回True.

参考视频虽然是老印口音,但是有字幕, 讲的还是很清楚的.

code 如下:

 1 class Solution:
 2     def checkLoopInDirectedGraph(self, graph, n): # n = number of nodes
 3         d = collections.Counter() #default value is 0, not visited
 4         def dfs(d, graph, i):
 5             if d[i] == -1: return False
 6             if d[i] == 1: return True
 7             d[i] = -1
 8             for neig in graph[i]:
 9                 if not dfs(d, graph, neig):
10                     return False
11             d[i] = 1
12             return True
13         for i in range(n):
14             if not dfs(d, graph, i):
15                 return False
16         return True

2) Check whether have loop in directed graph, if not loop, print path from start node to end, order does not matter for not connected, else return []

所以这个path的返回, 因为对不是联通的graph part的order无所谓, 所以我们只需要将以上的code加一行即可, 就是在visited node return True之前, 将其append进入到ans里面, 这样的话ans的顺序就是从尾巴print到node head, 所以返回的时候将ans reverse即可.

这个思路可以运用在

code如下:

 1 class Solution:
 2     def pathInDirectedGraph:(self, graph, n):
 3         d, ans = collections.Counter(), []
 4         def dfs(d, graph, i):
 5             if d[i] == 1: return True
 6             if d[i] == -1: return False
 7             d[i] = -1
 8             for neig in graph[i]:
 9                 if not dfs(d, graph, neig):
10                     return False
11             d[i] = 1
12             ans.append(i)
13             return True
14         for i in range(n):
15             if not dfs(d, graph, i):
16                 return []
17         return ans[::-1]   # remember to reverse the ans

原文地址:https://www.cnblogs.com/Johnsonxiong/p/9279415.html

时间: 2024-08-28 07:11:41

Directed Graph Loop detection and if not have, path to print all path.的相关文章

[email protected] Find if there is a path between two vertices in a directed graph

Given a Directed Graph and two vertices in it, check whether there is a path from the first given vertex to second. For example, in the following graph, there is a path from vertex 1 to 3. As another example, there is no path from 3 to 0. We can eith

[LintCode] Find the Weak Connected Component in the Directed Graph

Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a connected set of a directed graph is a subgraph in which any two vertices are connected by direct edge path.) Exam

Geeks - Detect Cycle in a Directed Graph 判断图是否有环

Detect Cycle in a Directed Graph 判断一个图是否有环,有环图如下: 这里唯一注意的就是,这是个有向图, 边组成一个环,不一定成环,因为方向可以不一致. 这里就是增加一个数组保存当前已经访问过的路径信息 recStack[]: 而visited[]数组是访问过的点的信息,两者作用是不一样的. 知道这个知识点,这道题就很容易了. 原文: http://www.geeksforgeeks.org/detect-cycle-in-a-graph/ #include <st

[CareerCup] 4.2 Route between Two Nodes in Directed Graph 有向图中两点的路径

4.2 Given a directed graph, design an algorithm to find out whether there is a route between two nodes. LeetCode和CareerCup中关于图的题都不是很多,LeetCode中只有三道,分别是Clone Graph 无向图的复制,Course Schedule 课程清单 和 Course Schedule II 课程清单之二.目前看来CareerCup中有关图的题在第四章中仅此一道,这是

CodeChef Counting on a directed graph

Counting on a directed graph Problem Code: GRAPHCNT All submissions for this problem are available. Read problems statements in Mandarin Chineseand Russian. Given an directed graph with N nodes (numbered from 1 to N) and M edges, calculate the number

Leetcode: Graph Valid Tree &amp;&amp; Summary: Detect cycle in directed graph and undirected graph

Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree. For example: Given n = 5 and edges = [[0, 1], [0, 2], [0, 3], [1, 4]], return tru

Geeks - Detect Cycle in a Directed Graph 推断图是否有环

Detect Cycle in a Directed Graph 推断一个图是否有环,有环图例如以下: 这里唯一注意的就是,这是个有向图, 边组成一个环,不一定成环,由于方向能够不一致. 这里就是添加一个数组保存当前已经訪问过的路径信息 recStack[]: 而visited[]数组是訪问过的点的信息,两者作用是不一样的. 知道这个知识点,这道题就非常easy了. 原文: http://www.geeksforgeeks.org/detect-cycle-in-a-graph/ #includ

Find the Weak Connected Component in the Directed Graph

Description Find the number Weak Connected Component in the directed graph. Each node in the graph contains a label and a list of its neighbors. (a weak connected component of a directed graph is a maximum subgraph in which any two vertices are conne

普林斯顿大学《算法II》第二周学习笔记 Directed Graph

有向图的遍历和无向图的遍历类似,主要是DFS和BFS. 对于DAG(Directed Acyclic Graph),还有一个很重要的拓扑的概念,拓扑排序的倒序可以用Depth-first search来生成,类似二叉树的后序遍历. 见Depthfirst Order in Algs4 private void dfs(Digraph G, int v) { marked[v] = true; pre[v] = preCounter++; preorder.enqueue(v); for (int