花花生米

导航

图的遍历

最后的输出顺序是1 2 3 5 4
也就是说,在访问每一个顶点的时候,会先对与此顶点有关联的点进行访问,再进行下一个;

#include <cstdio>

#include <iostream>

using namespace std;


int main()
{
	int i, j, n, m, a, b, cur, book[101] = { 0 }, e[101][101];
	int que[10001], head, tail;
	cin >> n >> m;
	//初始化二维矩阵
	for (i = 1; i <= n; i++)
	{
		for (j = 1; j <= n; j++)
		{
			if (i == j)e[i][j] = 0;
			else e[i][j] = 99999999;//设为正无穷
		}
	}
	//读入顶点之间的联系
	for (i = 1; i <= m; i++)
	{
		cin >> a >> b;
		e[a][b] = 1; e[b][a] = 1;
	}
	//队列的初始化
	head = 1; tail = 1;
	
	//将一号顶点加入队列
	que[tail] = 1; tail++; book[1] = 1;

	//循环
	while (head < tail && tail <= n)
	{
		//找到当前的顶点
		cur = que[head];
		for (i = 1; i <= n; i++)
		{
			//判断当前顶点与其他点是否构成连线
			if (e[cur][i] == 1 && book[i] == 0)
			{
				que[tail] = i; tail++; book[i] = 1;
			}
			if (tail > n)break;
		}
		head++;
	}
	for (i = 1; i < tail; i++)
	{
		printf("%d ", que[i]);

	}
	getchar(); getchar();
	return 0;
}

posted on 2020-08-21 17:44  花花生米  阅读(176)  评论(0编辑  收藏  举报