Implemented by the DFS algorithm in the introduction to algorithms.
As follows:
#include <stdio.h> enum {white, GRAY, BLACK};
struct vertex {int color;
int d, F;
int parent;
};
int time = 0;
void dfs_visit (int matrix[][6], struct vertex *v, int index);
void Dfs (int matrix[][6], struct vertex *v) {int i;
for (i = 0; i < 6; i++) {v[i].color = white;
V[I].D = 0;
V[I].F = 0;
V[i].parent =-1;
} for (i = 0; i < 6; i++) {if (V[i].color = =) {dfs_visit (Matrix, V, i);//printf ("\ n");
}}} int tmp[6];
int g_index = 0;
void dfs_visit (int matrix[][6], struct vertex *v, int index) {//printf ("%d", index);
if (V[index].color = = white) {Tmp[g_index] = index;
g_index++;
} time + = 1;
V[INDEX].D = time;
V[index].color = GRAY;
int i;
for (i = 0; i < 6, i++) {if (matrix[index][i] && v[i].color = = white) {v[i].parent = index;
Dfs_visit (Matrix, V, i);
} else if (V[i].color = = GRAY && matrix[index][i]) {int j = 0;
while (tmp[j]! = i) {j + +; } while (J < G_index) {printf ("%d-to", Tmp[j]);
j + +;
} printf ("%d\n", I);
}} time + = 1;
V[INDEX].F = time;
V[index].color =black;
g_index--; } int main (int argc, char **argv) {int matrix[6][6] = {{1, 1, 0, 1, 1, 0}, {0, 0, 1, 0, 0, 0}, {1, 0, 0, 0, 0,
0}, {0, 0, 0, 0, 1, 0}, {0, 0, 0, 0, 0, 1}, {0, 0, 0, 1, 0, 0}};
struct vertex v[6];
DFS (Matrix, v);
return 0; }
Output:
0-->0
0-->1-->2-->0
3-->4-->5-->3