图的深度优先搜索(非递归)

样例输入

4
0 1 0 1
1 0 0 0
0 0 0 1
1 0 1 0

样例输出

0 1 3 2
 1 #include <stdio.h>
 2 #include <memory.h>
 3 #define COUNT 55
 4 typedef struct {
 5     int arc[COUNT][COUNT];
 6     int verNum;
 7 }Graph;
 8 void create(Graph *G){
 9     scanf("%d",&G->verNum);
10     for(int i = 0; i < G->verNum; i++)
11         for(int j = 0; j < G->verNum; j++)
12             scanf("%d",&G->arc[i][j]);
13 }
14 void DFS(Graph G){//从结点0开始访问
15     int degree[COUNT];
16     int hang,lie;
17     int stack[COUNT],top = 0;
18     int arc;
19     stack[top++] = 0;
20     memset(degree,1,COUNT * sizeof(int));
21     while(top > 0){
22         arc = stack[top - 1];
23         if(degree[arc]){
24             printf("%d ",arc);
25             degree[arc] = 0;
26         }
27         for(lie = 0; lie < G.verNum; lie++){
28             if(G.arc[arc][lie] && degree[lie]){
29                 stack[top++] = lie;
30                 break;
31             }
32         }
33         if(lie == G.verNum)
34             arc = stack[--top];
35     }
36 }
37 int main(){
38     Graph G;
39     create(&G);
40     DFS(G);
41     printf("\n");
42     return 0;
43 }

 

 
posted @ 2016-05-19 22:27  赤云封天  阅读(408)  评论(0编辑  收藏  举报