말이 촌수계산이지 그냥 노드와 노드사이의 거리를 구하면 된다.
최소 길이를 구하면 되므로 시작노드를 기준으로 bfs돌리면 된다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| #include <iostream> #include <queue> using namespace std; queue<int> q; int n, m, a, b, c, d, cq, arr[102][102], v[102]; int main() { cin >> n >> a >> b >> m; for(int i = 0; i < m; i++) { cin >> c >> d; arr[c][d] = arr[d][c] = 1; } q.push(a); while(!q.empty()) { cq = q.front(); q.pop(); for(int i = 1; i <= n; i++) if(arr[cq][i] && !v[i]) q.push(i), v[i] = v[cq] + 1; } cout << (v[b] ? v[b] : -1); }
|