๐งจ ๋ฐฑ์ค 2644๋ฒ - ์ด์๊ณ์ฐ
๋ฌธ์ ๋์ด๋ : ์ค๋ฒ2
๋ฌธ์ ๋งํฌ : www.acmicpc.net/problem/2644
2644๋ฒ: ์ด์๊ณ์ฐ
์ฌ๋๋ค์ 1, 2, 3, …, n (1≤n≤100)์ ์ฐ์๋ ๋ฒํธ๋ก ๊ฐ๊ฐ ํ์๋๋ค. ์ ๋ ฅ ํ์ผ์ ์ฒซ์งธ ์ค์๋ ์ ์ฒด ์ฌ๋์ ์ n์ด ์ฃผ์ด์ง๊ณ , ๋์งธ ์ค์๋ ์ด์๋ฅผ ๊ณ์ฐํด์ผ ํ๋ ์๋ก ๋ค๋ฅธ ๋ ์ฌ๋์ ๋ฒํธ๊ฐ ์ฃผ์ด์ง
www.acmicpc.net
๐งจ ์๊ณ ๋ฆฌ์ฆ ์ ํ ๋ฐ C++ ์ฝ๋
DFS๋ฅผ ์ฐ๋ ์ค ์์๋๋ฐ ์ฝ๋์ ๊ฐ์ด ์ ์กํ์ ๋ ์๊ฐํด๋ดค๋๋ BFS๋ฅผ ํ์ฉํ ๋ฌธ์ ์๋ค. ๋๋น์ฐ์ ํ์์ผ๋ก ๊น์ด๋ฅผ ์นด์ดํ ํ๋ค. ์ ์ (์ฒซ ๋ ธ๋)์์ ๋ด๊ฐ ์ํ๋ ์ฌ๋๊น์ง ๊ฐ๋ ๊น์ด๋ง ์นด์ดํ ํ๋ ค ํ๋๋ฐ ์กฐ๊ฑด๋ฌธ ์ฐ๋ ๊ฒ ๋ ๋ณต์กํด์ ๊ทธ๋ฅ ๋ค ๊ณ์ฐํ๋ค. ์ ๋ ฅ๋ฐ์ start ์ฌ๋์์ ๋ชจ๋ ์ฌ๋๋ค๊น์ง์ ๊น์ด๋ฅผ ์นด์ดํ ํด depth ๋ฐฐ์ด์ ์ ์ฅํ๋ค. ์ ์๊ฐ๋ณด๋ค ์ฝ์ง ์์ ์ ๊ทผ์ด์๋๋ฐ ์ด๋ฐ ๋ฐฉ์์ ๋ฌธ์ ๋ ์์ผ๋ก ๋ง์ด ๋์ฌ ๊ฑฐ ๊ฐ๋ค..
#include <iostream>
#include <vector>
#include <utility>
#include <algorithm>
#include <queue>
using namespace std;
int n, x, y, m;
int isMarked[101] = {false};
void BFS(int G[101][101], int start, int end) {
int isMarked[101] = {false};
int isinQueue[101] = {false};
int depth[101] = {0};
queue<int> q;
q.push(start);
isinQueue[start] = true;
while(!q.empty()) {
int current = q.front();
q.pop();
isMarked[current] = true;
for(int i = 1; i < n + 1; i++) {
if(!isMarked[i] && !isinQueue[i] && G[current][i]) {
q.push(i);
isinQueue[i] = true;
depth[i] = depth[current] + 1;
}
}
}
if(depth[end] == 0) cout << -1;
else cout << depth[end];
return;
}
int main() {
cin >> n;
cin >> x >> y;
cin >> m;
int G[101][101] = {0};
for (int i = 0; i < m; i++) {
int parent, child;
cin >> parent >> child;
G[parent][child] = 1;
G[child][parent] = 1;
}
BFS(G, x, y);
return 0;
}
'Problem Solving > BOJ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[BOJ] ๋ฐฑ์ค 1012๋ฒ ์ ๊ธฐ๋ ๋ฐฐ์ถ (C++ ์ฝ๋) (0) | 2021.01.23 |
---|---|
[BOJ] ๋ฐฑ์ค 2178๋ฒ ๋ฏธ๋กํ์ (C++ ์ฝ๋) (0) | 2021.01.22 |
[BOJ] ์ ์ถ๋ ฅ๋ฌธ์ - getline, cin, %1d (0) | 2021.01.13 |
[BOJ] C++ ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด (3) (0) | 2021.01.12 |
[BOJ] C++ ๊ทธ๋ฆฌ๋ ์๊ณ ๋ฆฌ์ฆ ๋ฌธ์ ํ์ด (2) (0) | 2021.01.11 |