题目:详见啊哈算法P131页。就是如何给一个图,然后进行深度优先遍历。
分析:DFS入门。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int e[1000][1000];
int book[1000];
int n ;
int sum;
void dfs(int step){
printf("%d ",step);
sum ++ ;
if(sum == n+1) return ;
for(int i = 1 ; i <= n ; i++){
if(book[i]==0&&e[step][i]==1){
book[i] = 1 ;
dfs(i);
}
}
return ;
}
int main(){
freopen("in.txt","r",stdin);
int m , a , b ;
while(scanf("%d %d",&n,&m)!=EOF){
//³õʼ»¯
memset(book,0,sizeof(book));
for(int i = 1 ; i <= n ; i++){
for(int j = 1 ; j <= n ; j++){
if(i==j) e[i][j] = 1;
else e[i][j] = 999999;
}
}
//¶ÁÈëͼ
for(int i = 1 ; i <= m ; i++){
scanf("%d %d",&a,&b);
e[a][b] = 1 ;
e[b][a] = 1 ;
}
sum = 0 ;
book[1] = 1 ;
dfs(1);
}
return 0 ;
}