本文共 1185 字,大约阅读时间需要 3 分钟。
????????????????1????n????????????????????????BFS???????BFS??????????????
#include#include #include using namespace std;int main() { int k; // ?????? cin >> k; for (int test = 0; test < k; ++test) { int n, m; cin >> n >> m; vector > graph(n + 1); vector distance(n + 1, -1); queue q; distance[1] = 0; q.push(1); bool found = false; while (!q.empty()) { int u = q.front(); q.pop(); for (int v : graph[u]) { if (distance[v] == -1) { distance[v] = distance[u] + 1; if (v == n) { found = true; break; } q.push(v); } } if (found) break; } if (distance[n] == -1) { cout << "NO" << endl; } else { cout << distance[n] << endl; } } return 0;}
graph???????????????distance??????????????????????????????????????????
转载地址:http://pkexz.baihongyu.com/