菜鸟起飞

谁来教我用Emacs
栈版DFS

#include<iostream>

#include<stack>

using namespace std;

 

int g[100][100];//图

bool l[1000];//判环

int n,bg,ed;//图的大小,开始点结束点

stack<int> st;

 

void dfs(){

     memset(l,0,sizeof(l));

     int i,j=n,p;//p是指向节点的指针

     st.push(bg);

     while(j--){//节点个数

         p=st.top();

         st.pop();

         cout<<p<<endl;//留下遍历的脚印

         l[p]=1;//设为已连接过

         for(i=1;i<=n;i++)if(g[p][i]&&!l[i]){//将与p指向的节点连接的所有节点入栈

              st.push(i);

         }   

     }

}

int main()

{

     freopen("in.txt","r",stdin);

     //freopen("out.txt","w",stdout);

     int i,j;

     while(scanf("%d%d",&n,&bg)!=EOF){//输入图的大小和起始点

         for(i=1;i<=n;i++){

              for(j=1;j<=n;j++)

                   scanf("%d",&g[i][j]);//输入邻接矩阵

         }

         dfs();

     }

     return 0;

}

 

In.txt文件的内容:

7 1

0 1 0 0 0 0 0

0 0 1 1 0 0 0

0 0 0 0 1 1 1

1 0 0 0 0 0 0

0 0 0 0 0 0 0

0 0 0 0 0 0 0

0 0 0 0 0 0 0

posted on 2008-11-19 21:36  Jimmy55555!  阅读(228)  评论(0)    收藏  举报