有向图找环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); } } }