利用图的广度优先遍历解决城市最短路径问题

首先说明,这里的最短路是指经过的城市最少
代码如下:

/*
	广度优先遍历的应用:在城市地图中求一条
	一个城市到另一个城市的经过最少城市的路径
*/ 
#include
using namespace std;
#define N 10
int cityMap[N][N] = {{0}, {0, 0, 1, 1, 1, 0, 1, 0, 0}
					, {0, 1, 0, 0, 0, 0, 1, 0, 0}
					, {0, 1, 0, 0, 0, 0, 0, 0, 1}
					, {0, 1, 0, 0, 0, 0, 0, 1, 0}
					, {0, 0, 0, 0, 0, 0, 0, 0, 0}
					, {0, 1, 1, 0, 0, 0, 0, 0, 1}
					, {0, 0, 0, 0, 1, 0, 0, 0, 1}
					, {0, 0, 0, 1, 0, 0, 1, 1, 0}
					};
char cityName[N] = {'#', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};// 顶点 
int visited[N] = {0};// 标记图中元素的访问状态


void getPath(int k);
void outputShortestPath(int des);
int pre[N]; 
				
int main() {
	cout << "B到G的最短路径为:" << endl;
	getPath(2);

	return 0;
}

void getPath(int k) {
	int queue[N];
	pre[k] = -1;
	int front = 0, rear = 0;
	visited[k] = 1;
//	cout << cityName[k] << " ";
	queue[rear++] = k;
	while (front != rear) {
		int data = queue[front++];
		for (int i = 1; i <= 8; i++) {
			if (cityMap[data][i] == 1 && visited[i] == 0) {
//				cout << cityName[i] << " ";
				pre[i] = data;
				if (cityName[i] == 'G') {
					outputShortestPath(i);// 输出最短路径 
					return ;
				}
				
				queue[rear++] = i;
				visited[i] = 1;
			} 
		}
	}
}

void outputShortestPath(int des) {
	if (des == -1)
		return ;
	outputShortestPath(pre[des]);
	cout << cityName[des] << " ";
}

你可能感兴趣的:(算法设计与分析)