简单的图的深度优先遍历和广度优先遍历

    对图的遍历,深度优先遍历使用递归,广度优先遍历使用队列。

#include<stdio.h>


int book[100], queue[1000], e[100][100],sum,n;


void dfs(int cur)//深度优先搜索
{
	int i;
	printf_s("%d ", cur);//输出当前编号的值
	sum++;
	if (sum == n)//已经遍历完
		return;
	for (i = 1; i <= n; i++)
	{
		if (e[cur][i] == 1 && book[i] == 0)
		{
			book[i] = 1;
			dfs(i);//开始遍历i的以后节点
		}
	}
}



void bfs(int head,int tail, int n)//广度优先搜索,分别是队首队尾和节点数目
{
	while (head < tail)
	{
		int cur = queue[head];
		for (int i = 1; i <= n; i++)//从1到n依次尝试
		{
			if (e[cur][i] == 1 && book[i] == 0)//判断从顶点cur到i是否有边且顶点i是否被访问
			{
				queue[tail] = i;
				tail++;
				book[i] = 1;
			}
			if (tail > n)
				break;
		}
		head++;
	}
	for (int i=1; i < tail; i++)
		printf_s("%d ", queue[i]);

}


int main()
{
	int m, i, j, cur, head, tail, a, b;
	while (scanf_s("%d %d", &n, &m))//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] = 999999;
		}
		for (i = 1; i <= m; i++)//输入顶点之间的边
		{
			scanf_s("%d %d", &a, &b);
			e[a][b] = 1;
			e[b][a] = 1;
		}
		/*head = 1;
		tail = 1;
		queue[tail] = 1;
		tail++;
		book[1] = 1;
		bfs(head,tail,n);*/
		book[1] = 1;
		dfs(1);
	}
	getchar();
	return 0;
}

    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/ZYH920521/article/details/42009277
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞