图的遍历——BFS(队列实现)

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#include <malloc.h>

using namespace std;

const int VERTEX_NUM = 20;
const int INFINITY = 0x7fffffff; 		// 最大int型数,表示权的无限值 

bool vis[VERTEX_NUM];

class Graph {
public:
	int vexNum;
	int edgeNum;
	int vex[VERTEX_NUM];
	int arc[VERTEX_NUM][VERTEX_NUM]; 
};

void createGraph(Graph &G)
{
	cout << "please input vexNum and edgeNum: ";
	cin >> G.vexNum >> G.edgeNum;
	for (int i = 0; i != G.vexNum; ++i) {
		cout << "please input no" << i+1 << " vertex: ";
		cin >>  G.vex[i];
	}
	for (int i = 0; i != G.vexNum; ++i) {
		for (int j = 0; j != G.vexNum; ++j) {
			G.arc[i][j] = INFINITY;
		}
	}
	for (int k = 0; k != G.edgeNum; ++k) {
		cout << "please input the vertex of edge(vi, vj) and weight: ";
		int i, j, w;
		cin >> i >> j >> w;
		G.arc[i][j] = w;
		G.arc[j][i] = G.arc[i][j];			// 无向图 
	}
}

void BFSTraverse(const Graph &G)
{
	memset(vis, false, VERTEX_NUM);
	queue<int> q;
	for (int i = 0; i != G.vexNum; ++i) {
		if (!vis[i]) {
			vis[i] = true;
			cout << G.vex[i] << " ";
			q.push(i);
			while (!q.empty()) {
				int m = q.front();	// 队列的作用正在于此 
				q.pop();		// ...
				for (int j = 0; j != G.vexNum; ++j) {
					if (G.arc[m][j] != INFINITY && !vis[j]) {
						cout << G.vex[j] << " ";
						q.push(j);
						vis[j] = true;
					}
				}
			}
		}
	}
} 

int main()
{
	Graph G;
	createGraph(G);
	BFSTraverse(G);
	return 0;
} 

  

    原文作者:GGBeng
    原文地址: https://www.cnblogs.com/xzxl/p/8646694.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞