private void DFS(IDirectedGraph graph, int vertex) { onStack[vertex] = true; isConnected[vertex] = true; foreach (int v in graph.Adjacent(vertex)) { if (HasCycle()) { return; } if (!isConnected[v]) { edgeTo[v] = vertex; DFS(graph, v); } // 如果当前相邻顶点被标记过,并且在递归调用栈上,说明路径又回到了之前的顶点,也就是出现环路 else if (onStack[v]) { cycle = new Stack <int>(); // 把路径上的所有顶点记录下来 for (int i = vertex; i != v; i = edgeTo[i]) { cycle.Push(i); } cycle.Push(v); cycle.Push(vertex); } } onStack[vertex] = false; }
private void DFS(IDirectedGraph graph, int vertex) { isConnected[vertex] = true; id[vertex] = count; foreach (var v in graph.Adjacent(vertex)) { if (!isConnected[v]) { DFS(graph, v); } } }
private void DFS(IDirectedGraph graph, int vertex) { pre.Enqueue(vertex); isConnected[vertex] = true; foreach (int v in graph.Adjacent(vertex)) { if (!isConnected[v]) { DFS(graph, v); } } post.Enqueue(vertex); reversePost.Push(vertex); }