BFS与最短路问题小结 - AcWing
题目 这题就可以BFS(边权值相同)(g[i][j]也可以为inf,g[i][i]还能为0)
代码
#include <bits/stdc++.h>
using namespace std;
const int N = 510;
const int inf = 0x3f3f3f3f;
int n, m;
int a[N];
int dist[N];
int g[N][N];
bool st[N];
int dijkstra() // 求1号点到n号点的最短路距离
{
memset(dist, 0x3f, sizeof dist);
dist[1] = 0;
for(int i = 0; i < n; i++)
{
int t = -1;
for(int j = 1; j <= n; j++)
{
if(!st[j] && (t == -1 || dist[j] < dist[t]))
t = j;
}
st[t] = 1;
for(int j = 1; j <= n; j++)
dist[j] = min(dist[j], dist[t] + g[t][j]);
}
return dist[n] - 1;
}
int main()
{
cin >> m >> n;
memset(g, 0x3f, sizeof g);
for(int i = 1; i <= n; i++)
g[i][i] = 0;
getchar();
for(int i = 1; i <= m; i++)
{
string line;
getline(cin, line); // 读取整行输入
stringstream ss(line);
int station, cnt = 0;
while (ss >> station) // 逐个读取每一站的编号(成功返回引用,失败返回nullptr), 等同于scanf(成功返回成功个数,失败返回0或负)
a[++cnt] = station;
for (int j = 1; j <= cnt; j++) {
for (int k = j + 1; k <= cnt; k++) {
g[a[j]][a[k]] = min(g[a[j]][a[k]], 1);
}
}
}
int t = dijkstra();
cout << (t > inf/2 ? "NO" : to_string(t));
}