题解 | #【模板】单源最短路1#
【模板】单源最短路1
https://www.nowcoder.com/practice/f24504c9ff544f7c808f76693cc34af8
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
const int N = 5100;
struct Node
{
int id;
int step;
Node() {}
Node(int _id, int _step) :id(_id), step(_step) {}
};
vector<int> graph[N];
vector<int> vis(N);
int n, m;
int BFS(int start, int step)
{
Node node(start, step);
queue<Node> que;
que.push(node);
vis[start] = 1;
while (!que.empty())
{
Node s = que.front();
que.pop();
if (s.id == n)
{
return s.step;
}
for (int i = 0; i < graph[s.id].size(); i++)
{
if (vis[graph[s.id][i]] == 0)
{
vis[graph[s.id][i]] = 1;
que.push(Node(graph[s.id][i], s.step + 1));
}
}
}
return -1;
}
int main()
{
cin >> n >> m;
int x, y;
for (int i = 0; i < m; i++)
{
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
cout << BFS(1, 0) << endl;
return 0;
}
#include <vector>
#include <queue>
using namespace std;
const int N = 5100;
struct Node
{
int id;
int step;
Node() {}
Node(int _id, int _step) :id(_id), step(_step) {}
};
vector<int> graph[N];
vector<int> vis(N);
int n, m;
int BFS(int start, int step)
{
Node node(start, step);
queue<Node> que;
que.push(node);
vis[start] = 1;
while (!que.empty())
{
Node s = que.front();
que.pop();
if (s.id == n)
{
return s.step;
}
for (int i = 0; i < graph[s.id].size(); i++)
{
if (vis[graph[s.id][i]] == 0)
{
vis[graph[s.id][i]] = 1;
que.push(Node(graph[s.id][i], s.step + 1));
}
}
}
return -1;
}
int main()
{
cin >> n >> m;
int x, y;
for (int i = 0; i < m; i++)
{
cin >> x >> y;
graph[x].push_back(y);
graph[y].push_back(x);
}
cout << BFS(1, 0) << endl;
return 0;
}