欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

邻接矩阵的深度优先遍历和广度优先遍历(无向图)

程序员文章站 2022-06-13 11:46:01
...

邻接矩阵的深度优先遍历和广度优先遍历(无向图)

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<queue>
#include<iostream>
using namespace std;
#define MAXGRAPH 100

int visited[MAXGRAPH]; //访问过的顶点数组
typedef struct Graph_G
{
	char vertex[MAXGRAPH]; //顶点集
	int edge[MAXGRAPH][MAXGRAPH]; //边集(邻接矩阵)
	int n;   //当前的顶点数
	int e;   //当前的边数
}Graph;

void create_graph(Graph* G)
{
	memset(&(G->edge), 0, sizeof(G->edge));
	printf("输入顶点数:");
	scanf("%d", &G->n);
	printf("输入边数:");
	scanf("%d", &G->e);
	getchar();
	printf("输入顶点集合:");
	for (int i = 0; i < G->n; i++)
	{
		scanf("%c", &G->vertex[i]);
	}
	printf("输入边(顶点->顶点 权重):\n");
	int m, n, w;
	for (int i = 0; i < G->e; i++)
	{
		scanf("%d %d %d", &m, &n, &w);
		G->edge[m][n] = w;
		G->edge[n][m] = w;
	}
}

/*
深度优先遍历
*/
void DFS(Graph* G, int k)
{
	printf("访问顶点: %c\n", G->vertex[k]);
	visited[k] = 1;

	for (int i = 0; i < G->n; i++)
	{
		if (G->edge[k][i] != 0 && visited[i] == 0)
		{
			DFS(G, i);
		}
	}
}

/*
广度优先遍历
*/
void BFS(Graph* G, int k)
{
	queue<int> q;
	printf("访问顶点:%c\n", G->vertex[k]);
	visited[k] = 1;
	q.push(k); //入队列
	int val;
	while (!q.empty())  //队列不为空
	{
		val = q.front(); //返回队首元素
		q.pop();  //出队列
		for (int i = 0; i < G->n; i++)
		{
			if (G->edge[val][i] != 0 && visited[i] == 0)
			{
				printf("访问顶点:%c\n", G->vertex[i]);
				visited[i] = 1;
				q.push(i);
			}
		}
	}
}

int main()
{
	Graph G;
	create_graph(&G);
	memset(&visited, 0, sizeof(visited));
	//DFS(&G, 0); //0 代表从第一个输入的顶点开始遍历
	BFS(&G, 0);
	return 0;
}

邻接矩阵的深度优先遍历和广度优先遍历(无向图)

相关标签: C++ C