1. 程式人生 > 其它 >棧的非遞迴深度優先搜尋

棧的非遞迴深度優先搜尋

原文連結

#include<stdio.h>
#include<stack>
#define MAX 100
using namespace std;

typedef struct
{
    int e[MAX][MAX];
    int ves;
    int edge;
    int book[MAX];//標誌判斷是否有被訪問過 
}MGraph;

void createMGraph(MGraph *G)
{
    int i;
    int j;
    int start;
    int end;

    printf("please input the ves and edge:\n");
    scanf("%d %d",&G->ves,&G->edge);
//初始化
    for(i = 0; i < G->ves; i++)
    {
        for(j = 0; j < G->ves; j++)
            G->e[i][j] = 0;
        G->book[i] = 0;//沒被訪問過的結點置為0 
    }
//建立鄰接矩陣 
    printf("please input the (vi,vj)\n");
    for(i = 0; i < G->edge; i++)
    {
        scanf("%d %d",&start,&end);
        G->e[start][end] = 1;
    }
}

void dfs(MGraph* G,int ves)
{
   stack<int> s;//建立一個棧
   printf("%d ", ves);

   G->book[ves] = 1;//已經訪問過結點ves了
   s.push(ves);//入棧

   while(!s.empty())
   {
       int data, i;

       data = s.top();//取top的頂點
       for(i = 0; i < G->ves; i++)
       {
           if(G->e[data][i] != 0 && G->book[i] != 1)
       	   {
           printf("%d ", i);
           G->book[i] = 1;
           s.push(i);
           break;// 開始遍歷下一個點的鄰接矩陣表
      	   }
       }
       if(i == G->ves)//data相鄰的結點都訪問結束了,就彈出data
       {
           s.pop();
       }
   }
}

int main()
{
    MGraph G;
    createMGraph(&G);
    dfs(&G,0);
    return 0;
}
/*
輸入樣例:
8 18
0 1
0 2
1 0
1 3
1 4
2 0
2 5
2 6
3 1
3 7
4 1
4 7
5 2
5 6
6 2
6 5
7 3
7 4
*/