图的广度优先搜索可以解决:无权重、固定两点最短路径
题目描述
遍历上图,输出1->5最短路径长度(各边权值均为1)
Input
5 7 1 5
1 2
1 3
2 3
2 4
3 4
3 5
4 5
n m start end:表示有n个城市,m条边,起点,终点
a b:表示a城市到b城市连通
代码如下
#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
#define SIZE 101
using namespace std;
struct node
{
int x,s;
};
int e[SIZE][SIZE],book[SIZE],n,m,start,End;
void bfs()
{
queue<node> q;
node now;
now.x = start;
now.s = 0;
book[start] = 1;
q.push(now);
while(!q.empty())
{
now = q.front();
q.pop();
for(int i = 1;i <= n;i++)
{
node next;
next.x = i;
if(e[now.x][next.x] != INT_MAX && !book[next.x])
{
next.s += (now.s + 1);
book[next.x] = 1;
q.push(next);
}
if(next.x == End)
{
printf("%d\n",next.s);
return;
}
}
}
}
int main()
{
int i,j,a,b,c;
scanf("%d %d %d %d",&n,&m,&start,&End);
//初始化邻接矩阵
for(i = 1;i <= n;i++)
{
for(j = 1;j <= n;j++)
{
if(i == j)
e[i][j] = 0;
else
e[i][j] = INT_MAX;
}
}
//无向图
for(i = 0;i < m;i++)
{
scanf("%d %d",&a,&b);
e[a][b] = 1;
e[b][a] = 1;
}
bfs();
return 0;
}