DS图遍历--深度优先搜索

Description

给出一个图的邻接矩阵,对图进行深度优先搜索,从顶点0开始

注意:图n个顶点编号从0到n-1

如果图不连通,则对尚未访问的编号结点继续进行深度优先搜索,直到所有结点被访问

Input

第一行输入t,表示有t个测试实例

第二行输入n,表示第1个图有n个结点

第三行起,每行输入邻接矩阵的一行,以此类推输入n行

第i个结点与其他结点如果相连则为1,无连接则为0,数据之间用空格隔开

以此类推输入下一个示例

Output

每行输出一个图的深度优先搜索结果,结点编号之间用空格隔开

Sample

#0
Input
2
4
0 0 1 1
0 0 1 1
1 1 0 1
1 1 1 0
5
0 0 0 1 1
0 0 1 0 0
0 1 0 1 1
1 0 1 0 0
1 0 1 0 0
Output
0 2 1 3 
0 3 2 1 4 
#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
#include<stack>
using namespace std;

int main()
{
	int t;
	cin >> t;
	while (t--)
	{
		int n;
		cin >> n;

		int* check = new int[n];
		int** martix = new int*[n];
		for (int i = 0; i < n; i++)
		{
			martix[i] = new int[n];
			check[i] = 0;
		}

		for (int i = 0; i < n; i++)
			for (int j = 0; j < n; j++)
				cin >> martix[i][j];

		while (true)
		{
			int i;
			for (i = 0; i < n; i++)
				if (!check[i])
					break;
			if (i == n)
				break;

			stack<int> a;
			a.push(i);
			if (!check[i])
				cout << i << " ";
			check[i] = 1;
			while(!a.empty())
			{
				int j;
				i = a.top();
				for (j = 0; j < n; j++)
				{
					if (martix[i][j] && !check[j])
					{
						cout << j << " ";
						check[j] = 1;
						a.push(j);
						break;
					}
				}
				if(j==n)
					a.pop();
			}
		}
		cout << endl;
	}

	return 0;
}

  • 11
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值