题解 | 【模板】单源最短路Ⅰ ‖ 无权图
【模板】单源最短路Ⅰ ‖ 无权图
https://www.nowcoder.com/practice/359e14832ce1476fadc70dd4bc36b991?tpId=376&tags=&title=&difficulty=0&judgeStatus=0&rp=0&sourceUrl=%2Fexam%2Foj%3FquestionJobId%3D10%26subTabName%3Donline_coding_page
step1:创建一个数组,表示从起点s到每个顶点的最短路径。初始化值为-1。
step2:创建一个队列,起点s的最短路径设为0,将起点s加入队列中。
step3:从队列首部取出一个顶点u,依次判断该顶点连接到的每一个顶点v。若v的最短路径为-1,则更新为u的最短路径+1,并将v加入到队列末尾。
step4:重复step3,直至队列为空。
因为一个顶点u可能连接到多个顶点v,因此这里用到哈希表,哈希表的key为顶点编号,value为v的数组。
下面是代码。
#include <iostream>
#include <queue>
#include <unordered_map>
#include <vector>
using namespace std;
int main() {
int n, m, s, u, v;
cin >> n >> m >> s;
vector<int> len(n + 1, -1);
unordered_map<int, vector<int>> mp;
for (int i = 0; i < m; ++i) {
cin >> u >> v;
mp[u].push_back(v);
}
queue<int> q;
len[s] = 0;
q.push(s);
while (!q.empty()) {
int x = q.front();
q.pop();
if (mp.find(x) != mp.end()) {
for (int& v : mp[x]) {
if (len[v] == -1) {
q.push(v);
len[v] = len[x] + 1;
}
}
}
}
for (int i = 1; i <= n; ++i) {
cout << len[i] << " ";
}
}
// 64 位输出请用 printf("%lld")
查看13道真题和解析