原题链接

图的边权相等,统计优先步数到达某个节点的方案数一般用 BFS、DFS 就可以。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
class Solution {
public:
int numWays(int n, vector<vector<int>>& r, int k) {
unordered_map<int, unordered_set<int>> m;
for (auto& x : r) {
int a = x[0], b = x[1];

if (m.count(a)) {
m[a].insert(b);
} else {
unordered_set<int> s;
s.insert(b);
m[a] = s;
}
}
queue<int> q;
q.push(0);
while (q.size() && k-- > 0) {
int len = q.size();
while (len--) {
auto t = q.front();
q.pop();
if (!m.count(t)) continue;
auto s = m[t];
for (int ne : s) {
q.push(ne);
}
}
}
int ans = 0;
while (q.size()) {
if (q.front() == n - 1) ans++;
q.pop();
}
return ans;
}
};