반응형
백준 2644 촌수계산
- 완전 탐색 문제이다.
- https://www.acmicpc.net/problem/2644
- 문제풀이
1) 주어지는 좌표(촌수)에 대한 그래프를 생성한 후, 시작 좌표(촌수) 끝 좌표(촌수)의 거리를 구하면 되는 문제이기 BFS, DFS 둘 중 하나를 쓰면된다.
2) 나는 BFS가 더 편하기에 BFS를 사용했다..
#include<iostream> #include<stack> #include<vector> #include<queue> #include<string.h> using namespace std; int a[102][102]; queue<int> q; int check[102]; int n, s, e, m, x, y; void input_data() { cin >> n >> s >> e >> m; for (int i = 0; i < m; i++) { cin >> x >> y; //그래프 연결 a[x][y] = 1; a[y][x] = 1; } q.push(s); check[s] = 1; } int bfs() { while (!q.empty()) { int x = q.front(); q.pop(); if (x == e) { return check[x]; //찾음; } for (int i = 1; i <= n; i++) { int y = a[x][i]; if (y == 1 && check[i]==0) { // << "y:" << y << " "; check[i] = check[x] + 1; q.push(i); } } } return 0; } int main(void) { input_data(); int ans = bfs(); if (ans == 0) cout << -1; else cout << ans-1; }
반응형
'알고리즘 > acmicpc' 카테고리의 다른 글
[백준][1600번] 말이 되고픈 원숭이 [cpp, c++] (1) | 2020.03.19 |
---|---|
[백준][1629번] 곱셈[cpp, c++] (0) | 2020.02.16 |
[백준][9466번] 텀 프로젝트[cpp, c++] (0) | 2020.02.14 |
[백준][6593번] 상범 빌딩[cpp, c++] (0) | 2020.02.12 |
[백준][2146번] 다리 만들기[cpp, c++] (0) | 2020.02.01 |