반응형
최단거리를 구하는 문제입니다. BFS를 이용하여 풀었습니다
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 | #include <iostream> #include <queue> #include <vector> using namespace std; vector <int> family[101]; queue <int> q; int n, m, a, b; bool c[101]; int d[101]; int BFS(int x) { q.push(x); c[x] = 1; while (!q.empty()) { int x = q.front(); q.pop(); for (int i = 0; i < family[x].size(); i++) { int y = family[x][i]; if (c[y] == 0) { q.push(y); c[y] = 1; d[y] = d[x] + 1; if (y == b) return d[y]; } } } return -1; } int main() { cin >> n; cin >> a >> b; cin >> m; while (m--) { int x, y; cin >> x >> y; family[x].push_back(y); family[y].push_back(x); } cout << BFS(a) << '\n'; } | cs |
'Algorithm' 카테고리의 다른 글
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 13229번:Selection Sum답 (0) | 2017.04.15 |
---|---|
(C++) - 백준(BOJ) 10974번 : 모든 순열 답 (0) | 2017.04.15 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 2783번:삼각 김밥 답 (0) | 2017.04.07 |
(C++) - 백준(BOJ) 2684 : 동전 게임 답 (0) | 2017.04.07 |
C++(씨쁠쁠)(cplusplus)-백준(baekjoon)(BaekJoon)코딩 2954번:창영이의 일기장 답 (0) | 2017.04.07 |