图的遍历-dfs
Description
一个有n个节点的连通图,这些节点以编号:1、2、……n进行编号,现给出节点间的连接关系。请以节点1为起点,按dfs的顺序遍历并输出该图。
Input
第一行为两整数,n和e,表示n个顶点,e条边
以下e行每行两个数,表示两个节点是联通的
Output
只有一行,为节点的dfs顺序
Sample Input 1
5 7 1 2 1 3 1 4 2 4 2 5 3 5 4 5
Sample Output 1
1 2 4 5 3
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
int s[1000][1000];//邻接矩阵
int a[1000];//将dfs遍历序列储存在里面
int x[1000];//相当于visited数组
int j=0;
void dfs(int t, int n)
{
a[j++] = t;
x[t] = 1;
for (int i = 1; i <= n; i++) {
if (s[t][i] == 1 && x[i] != 1)
dfs(i, n);
}
}
int main() {
int m, n;
while (cin >> m >> n) {
memset(x, 0, sizeof(x));
memset(x, 0, sizeof(x));
int y, z;
for (int i = 0; i < n; i++) {
cin >> y >> z;
s[y][z] = s[z][y] = 1;//输入边
}
dfs(1, m);
for (int i = 0; i < m - 1; i++)
cout << a[i] << " ";
cout << a[m - 1] << endl;
}
return 0;
}