Directed Graph Loop detection and if not have, path to print all path.
Posted johnsonxiong
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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
以上是关于Directed Graph Loop detection and if not have, path to print all path.的主要内容,如果未能解决你的问题,请参考以下文章
LintCode Find the Weak Connected Component in the Directed Graph
Detect Cycle In Directed/Undirected Graph
Find the Weak Connected Component in the Directed Graph
[LintCode] Find the Weak Connected Component in the Directed Graph
Codeforces Round #550 (Div. 3) F. Graph Without Long Directed Paths
Codeforces Round #550 (Div. 3) F. Graph Without Long Directed Paths