알고리즘 문제/BOJ
2644번 촌수계산
parkit
2018. 8. 29. 23:04
728x90
반응형
쉬운 문제였다.
전형적인 BFS 문제이다.
https://www.acmicpc.net/problem/2644
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 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 | #include <iostream> #include <queue> #include <cstdio> #include <vector> #include <cstring> #include <string> #include <math.h> #include <algorithm> using namespace std; int n = 0, m = 0; int sv = 0, ev = 0; vector<vector<int> > v; bool visit[101] = { false, }; queue<int> q; int BFS(int start) { q.push(start); int ret = 0; while (!q.empty()) { int qSize = q.size(); while (qSize--) { int here = q.front(); q.pop(); if (here == ev) { return ret; } if (visit[here]) continue; visit[here] = true; for (int next : v[here]) { if (!visit[next]) { q.push(next); } } } ++ret; } return -1; } int main(void) { scanf("%d", &n); v.resize(n + 1); scanf("%d %d", &sv, &ev); scanf("%d", &m); int left = 0, right = 0; while (m--) { scanf("%d %d", &left, &right); v[left].push_back(right); v[right].push_back(left); } printf("%d\n", BFS(sv)); return 0; } | cs |
728x90
반응형