图的深度广度优先搜索

深度

  1 #include <iostream>
  2 #include <cstdio>
  3 #define max 100
  4 using namespace std;
  5 bool visited[max]={0};
  6 
  7 typedef struct node
  8 {
  9     int Vertix[max];
 10     int relation[max][max];
 11     int V,R;
 12 }MGraph;
 13 //获取顶点下标
 14 int locateV(MGraph *M,int x)
 15 {
 16     for(int i=0;i<M->V;i++)
 17     {
 18         if(M->Vertix[i]==x)
 19             return i;
 20     }
 21 }
 22 //构造无向图
 23 void Creat_WX(MGraph *M)
 24 {
 25     scanf("%d%d",&M->V,&M->R);
 26     for(int i=0;i<M->V;i++)
 27     {
 28         scanf("%d",&M->Vertix[i]);
 29     }
 30     for(int i=0;i<M->V;i++)
 31     {
 32         for(int j=0;j<M->V;j++)
 33         {
 34             M->relation[i][j]=0;
 35         }
 36     }
 37     for(int i=0;i<M->R;i++)
 38     {
 39         int v1,v2;
 40         scanf("%d%d",&v1,&v2);
 41         int x1 = locateV(M,v1);
 42         int y1 = locateV(M,v2);
 43         M->relation[x1][y1]=1;
 44         M->relation[y1][x1]=1;
 45     }
 46 }
 47 int FirstIdx(MGraph *M,int v)
 48 {
 49     for(int i=0;i<M->V;i++)
 50     {
 51         if(M->relation[i][v])
 52         {
 53             return i;
 54         }
 55     }
 56     return -1;
 57 }
 58 int NextIdx(MGraph *M,int v,int w)
 59 {
 60     for(int i=w+1;i<M->V;i++)
 61     {
 62         if(M->relation[i][v])
 63         {
 64             return i;
 65         }
 66     }
 67     return -1;
 68 }
 69 void DFS(MGraph *M,int v)
 70 {
 71     visited[v]=1;
 72     printf("%d ",M->Vertix[v]);
 73 
 74     for(int i=FirstIdx(M,v);i>=0;i=NextIdx(M,v,i))
 75     {
 76         if(!visited[i])
 77             DFS(M,i);
 78     }
 79 }
 80 void DFSTraverse(MGraph *M)
 81 {
 82     int v;
 83     for(v=0;v<M->V;v++)
 84     {
 85         if(!visited[v])
 86         {
 87             DFS(M,v);
 88         }
 89     }
 90 }
 91 int main()
 92 {
 93     MGraph M;
 94     Creat_WX(&M);
 95     for(int i=0;i<M.V;i++)
 96     {
 97         for(int j=0;j<M.V;j++)
 98         {
 99             printf("%d ",M.relation[i][j]);
100         }
101         printf("\n");
102     }
103     DFSTraverse(&M);
104 }
105 /*
106 测试样例
107 8 9
108 1 2 3 4 5 6 7 8
109 1 2
110 2 4
111 2 5
112 4 8
113 5 8
114 1 3
115 3 6
116 6 7
117 7 3
118 */

猜你喜欢

转载自www.cnblogs.com/moumangtai/p/10084029.html