赞
踩
有向图如下
要求找出最大环中节点的个数,比如0-1-2-3-4构成一个环,0-1构成一个环,1-2也是一个环
其中0-1-2-3-4是最大环,环数为5
visit数组表示当前点的状态
0 表示还没访问过
1 表示正在访问
-1 表示访问结束
递归遍历的实现
- #include<iostream>
- #include<vector>
- using namespace std;
- vector<vector<int>> map;//邻接矩阵
- vector<int> visit;// 状态数组
- vector<int> path;//环的元素
- int v, e;
- int m = 0;
- int max = 0;
- void dfs(int k) {
- visit[k] = 1;
- path[m++] = k;
- for (int i = 0; i < v; i++) {
- if (map[k][i] == 1) {
- if (visit[i] == 0) {
- dfs(i);
- }
- if (visit[i] == 1) {
- cout << "环:";
- int cnt = 0;
- for (int j = m - 1;; j--) {
- cout << path[j] << ' ';
- cnt++;
- if (path[j] == i) {
- break;
- }
- }
- cout << endl;
- if (cnt > max) {
- max = cnt;
- }
- }
- //if (visit[i] == 0) {
- // continue;
- //}
- }
- }
- visit[k] = -1;
- m--;
- }
- int main() {
- while (cin >> v >> e) {
- vector<vector<int>>(v, vector<int>(v, 0)).swap(map);
- vector<int>(v, 0).swap(visit);
- vector<int>(v, 0).swap(path);
-
- for (int i = 1; i <= e; i++) {
- int a, b;
- cin >> a >> b;
- map[a][b] = 1;
- }
- cout << endl;
- for (int i = 0; i < v; i++) {
- for (int j = 0; j < v; j++) {
- cout << map[i][j] << " ";
- }
- cout << endl;
- }
- cout << endl;
- for (int i = 0; i < v; i++) {
- if (visit[i] != -1)
- dfs(i);
- }
- cout << max << endl;
- max = 0;
- }
- return 0;
- }
- 5 8
- 0 1
- 1 0
- 1 2
- 2 1
- 2 3
- 3 4
- 4 3
- 4 0
-
- 0 1 0 0 0
- 1 0 1 0 0
- 0 1 0 1 0
- 0 0 0 0 1
- 1 0 0 1 0
-
- 环:1 0
- 环:2 1
- 环:4 3 2 1 0
- 环:4 3
- 5
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。