首页 > 其他 > 详细

Data Structure Graph: cycle in a directed graph

时间:2014-04-19 07:24:01      阅读:522      评论:0      收藏:0      [点我收藏+]

geeks上的解答复杂了些,用回溯就行了

bubuko.com,布布扣
 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <queue>
 5 #include <stack>
 6 #include <string>
 7 #include <fstream>
 8 using namespace std;
 9 
10 const int N = 5;
11 vector<int> trace;
12 vector<bool> visit(N);
13 int graph[N][N] = {{1, 1, 0, 0, 0},
14                    {0, 0, 1, 0, 0},
15                    {0, 0, 0, 1, 1},
16                    {0, 1, 0, 0, 1},
17                    {1, 0, 0, 0, 0}};
18 
19 void cycle(int v) {
20     if (visit[v]) {
21         int beg = 0;
22         for (; beg < trace.size(); ++beg)
23             if (trace[beg] == v) break;
24         for (int i = beg; i < trace.size(); i++) {
25             cout << trace[i] << " ";
26         }
27         cout << endl;
28         return;
29     }
30     visit[v] = true;
31     trace.push_back(v);
32     for (int i = 0; i < N; i++) {
33         if (graph[v][i]) cycle(i);
34     }
35     trace.pop_back();
36     visit[v] = false;
37 }
38 
39 int main() {
40     cycle(0);
41     return 0;
42 }
bubuko.com,布布扣

 

Data Structure Graph: cycle in a directed graph,布布扣,bubuko.com

Data Structure Graph: cycle in a directed graph

原文:http://www.cnblogs.com/yingzhongwen/p/3674532.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!