1. 程式人生 > 實用技巧 >有向圖找環DFS

有向圖找環DFS

//歡迎指正!!!//


//
有向圖找環
//輸入n條邊
const int maxvex = 500; int graph[maxvex][maxvex] = {0};//鄰接矩陣 set<int>vexs;//頂點容器 bool visitted[maxvex] = {false};//訪問陣列 vector<vector<int>>ans;//路徑容器 void CreatGraph() { int eages = 0; cin >> eages; int first, second; for (int i = 0; i < eages; ++i) { cin
>> first >> second; graph[first][second] = 1; vexs.insert(first); } } void Dfs(int x, int& count, queue<int> routes) { if (visitted[x]) {//存在環 count++; queue<int>routes1(routes); vector<int>temp; while (routes1.front() != x) { routes1.pop(); }
while (!routes1.empty()) { temp.push_back(routes1.front()); routes1.pop(); } ans.push_back(temp); } else { visitted[x] = true; routes.push(x); set<int>::iterator it; for (it = vexs.begin(); it != vexs.end(); ++it) {
if (graph[x][(*it)]) { Dfs((*it), count, routes); } } } } void CheckCircle() { int count = 0;//環的數量 queue<int>routes;//儲存可能的環 set<int>::iterator it; for (it = vexs.begin(); it!=vexs.end(); ++it) { if (!visitted[(*it)]) { Dfs((*it), count, routes); } } }