Data Structure Graph: cycle in a directed graph

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

 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 }

 

你可能感兴趣的:(struct)