码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2016-05-19 23:20:19      阅读:419      评论:0      收藏:0      [点我收藏+]

标签:

样例输入

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 }

 

 

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

标签:

原文地址:http://www.cnblogs.com/yfs123456/p/5510440.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!