给定一个有N个顶点和E条边的无向图,顶点从0到N−1编号。请判断给定的两个顶点之间是否有路径存在。如果存在,给出最短路径长度。 这里定义顶点到自身的最短路径长度为0。 进行搜索时,假设我们总是从编号最小的顶点出发,按编号递增的顺序访问邻接点。
输入第1行给出2个整数N(0<N≤10)和E,分别是图的顶点数和边数。 随后E行,每行给出一条边的两个顶点。每行中的数字之间用1空格分隔。 最后一行给出两个顶点编号i,j(0≤i,j<N),i和j之间用空格分隔。
如果i和j之间存在路径,则输出"The length of the shortest path between i and j is X.",X为最短路径长度, 否则输出"There is no path between i and j."。
7 6 0 1 2 3 1 4 0 2 1 3 5 6 0 3
结尾无空行
The length of the shortest path between 0 and 3 is 2.
结尾无空行
#include<bits/stdc++.h> using namespace std; int pre[100]; int Map[505][505]; int dis[505]; bool vis[505] = { false }; int Min; #define INF 0x3f3f3f int find(int x) { if (pre[x] == x) return x; else return pre[x] = find(pre[x]); } void merge(int x, int y) { int xx = find(x); int yy = find(y); if (xx != yy) pre[xx] = yy; } void Dijkstra(int v, int n, int d) { dis[v] = 0; vis[v] = true; for (int i = 0; i < n; i++) //每次求得起始点到某个v顶点的最短路径,并加到vis集 { Min = INF; for (int k = 0; k < n; k++) { if (!vis[k]) { if (dis[k] < Min) { Min = dis[k]; v = k; //以下v已经改变 } } } vis[v] = true; //离起始点最近的点加入vis集 for (int k = 0; k < n; k++) //更新当前最短路径及距离 { if (!vis[k] && Min + Map[v][k] < dis[k]) { dis[k] = Min + Map[v][k]; } } } } int main() { int i, j, n, m, a, b, k1, k2; cin >> n >> m; for (i = 0; i < 100; i++) { pre[i] = i; } for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { Map[i][j] = Map[j][i] = INF; //设置为双向连通,并初始化为最大值 } } for (i = 0; i < m; i++) { cin >> a >> b; merge(a, b); Map[a][b] = Map[b][a] = 1; } cin >> k1 >> k2; for (int i = 0; i < n; i++) { dis[i] = Map[i][k1]; //Map[i][k1]为点i到起始点的直接距离(i到k1的弧) } if (find(k1) == find(k2)) { Dijkstra(k1, n, k2); printf("The length of the shortest path between %d and %d is %d.", k1, k2, dis[k2]); } else printf("There is no path between %d and %d.", k1, k2); return 0; }