Graph (undirected graph of park guide system, stored using adjacency matrix)

Design a simple tour guide system for a park, and design data structures and algorithms to realize corresponding functions. Requirements:
(1) Contains no less than 8 scenic spots. The vertices in the figure represent the scenic spots in the park, including the name of the scenic spot, the introduction of the scenic spot and other information; the path is represented by the edge, and the weight on the edge represents the distance between the scenic spots
;
Query related information of scenic spots;
(4) Provide tourists with a shortest path between any two scenic spots;
the graph I designed:
insert image description here
the adjacency matrix of the graph:
insert image description here

#include<bits/stdc++.h>
using namespace std;
int Map[100][100];//图的邻接矩阵

//初始化邻接矩阵,需要传入图的路劲数,和图的节点数
void Init(int n,int m) {
    
    
	//舍弃数组第0的位置
	for (int i = 1; i <= m;i++) {
    
    
		for (int j = 1; j <= m;j++) {
    
    
			Map[i][j] = i != j ? 1000 : 0;
		}
	}
	while (n--) {
    
    
		int i, j, c;
		cin >> i >> j >> c;
		Map[i][j] = Map[j][i] = c;//这种就是无向图
	}
	
}

int Path[10][10] = {
    
    0};//储存路劲节点的前驱
int D[10][10] = {
    
    0};//储存最短的路径

void Floyed(int m) {
    
    
	for (int i = 1; i <= m;i++) {
    
    
		for (int j = 1; j <= m;j++) {
    
    
			D[i][j] = Map[i][j];//这个位置赋值也为了下面三层循环使用
			if (D[i][j]<1000&&i!=j) {
    
    
				Path[i][j] = i;//这个位置说明从i能到j,但不一定是最近的
			}
			else {
    
    
				Path[i][j] = -1;//这样就说明i到j之间没有直接路劲
			}
		}
	}
	for (int k = 1; k <= m;k++) {
    
    
		for (int i = 1; i <= m;i++) {
    
    
			for (int j = 1; j <= m;j++) {
    
    
				//这句话的意思就是以k节点作为中间节点如果从i到k+在从k到j的值小于原本从i到j路劲的值,就可以换条路走
				if (D[i][k]+D[k][j]<D[i][j]) {
    
    
					D[i][j] = D[i][k] + D[k][j];
					//更新j的节点前驱,表示原来从i->j的路换成从i->k->j更近,注意这里的k节点的前驱为i并没有修改这个值
					Path[i][j] = k;
				}
			}
		}
	}
}

//得到从i到j的路径
list<int> GetPath (int i,int j) {
    
    
	list<int> lis;
	lis.push_back(j);
	int k = Path[i][j];
	while (k!=i) {
    
    
		lis.push_back(k);
		k = Path[i][k];
	}
	lis.push_back(k);
	lis.reverse();//翻转列表
	return lis;
}

int main() {
    
    
	int n, m;
	//节点,和路径的数目
	cin >> m >> n;
	Init(n,m);
	Floyed(m);
	list<int> l = GetPath(1 ,8);
	cout<<"从a到h的路径";
	for (int i: l) {
    
    
		cout << i<<"->";
	}
	return 0;
}

Test Data

8 14
1 2 4
1 3 3
2 3 3
2 4 5
2 5 9
3 4 5
3 8 5
4 5 7
4 6 6
4 7 5
4 8 4
5 6 3
6 7 2
7 8 6

Guess you like

Origin blog.csdn.net/blastospore/article/details/122130154