图的遍历-dfs

图的遍历-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;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值