使用DFS進行拓撲排序,如果可以完成的話,輸出路徑

2021-08-08 08:34:54 字數 1130 閱讀 7696

進行深度優先搜尋的時候,如果當前訪問的點是已經被訪問過的節點的話,說明出現了逆邊。因此有環,無法完成拓撲排序。

如果可以完成拓撲排序,檢測點序列就是乙個合法的拓撲排序!

#include 

#include

using

namespace

std;

class solution

cout

<< endl;}}

bool dfs(int s)

else

if (visited[nextv] == 1)

return

false;

}visited[s] = 2;

path.push_back(s); // 將檢測點加入到path中

return

true;

}public:

bool canfinish(int numcourses, vector

int, int> > &prerequisites)

// dispgraph();

visited = vector

(numcourses, 0);

for (int i = 0; i < numcourses; ++i)

}cout

<< "path is : ";

for (int i = 0; i < path.size(); ++i)

cout

<< path[i] << " ";

cout

<< endl;

return

true;

}};int main()

cout

<< solution().canfinish(numcourse, prerequisites) << endl;

return0;}

/*5 6

0 22 3

3 40 1

1 21 3

output:

path is: 4 3 2 1 0

15 7

0 22 3

3 40 1

1 21 3

4 3output:

0*/

拓撲排序 dfs

運用dfs,對乙個有向無回圖 dag 進行拓撲排序。乙個圖的拓撲排序可看成所有頂點沿水平線排列而成的乙個序列,使得所有有向邊均從左指向右。topological sort g call dfs g to compute finishing times f v for each vertex v as...

拓撲排序 dfs

include include includeusing namespace std const int maxn 50 typedef struct nodenode typedef struct graphgraph vectorss 存放拓撲序列 bool vis maxn int find ...

拓撲排序DFS做法

1 給定乙個有向圖,在拓撲排序中可以 有很多個正確解 由若干小段的 list 組成。2 正確的單序列順序 具體到乙個list之間的元素 3 正確的全序列順序 list彼此之間的順序,可以有多個 e.g.以下圖為例,不論先從哪個點開始 dfs,例如 dfs belt 會得到乙個 belt jacket...