根据“算法导论”中的DFS算法实现。
如下:
#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 == WHITE) { 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 -->", 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; }
输出:
0 -->0 0 -->1 -->2 -->0 3 -->4 -->5 -->3