https://www.acmicpc.net/problem/2644
๐จ๐ฉ๐ง ์๋ฐ๋ก ํธ๋ ์ด์ ๊ณ์ฐ (๋ฐฑ์ค 2644)
๐ ๋ฌธ์ ๊ฐ์
- ์ฌ๋ ์ n๊ณผ ๋ ์ฌ๋ x, y๊ฐ ์ฃผ์ด์ง
- l๊ฐ์ ๋ถ๋ชจ-์์ ๊ด๊ณ๋ ์ ๋ ฅ๋จ
- ๋ ์ฌ๋ ๊ฐ์ ์ด์๋ฅผ ๊ณ์ฐํ๋ ๋ฌธ์
์ด์๋?
- ๋ถ๋ชจ์ ์์์ 1์ด, ํ์ ๋ 2์ด
- ๋ถ๋ชจ-์์ ๊ด๊ณ๋ง ์ฃผ์ด์ง๋ฏ๋ก ๊ทธ๋ํ๋ ๋ฌด๋ฐฉํฅ ์ฐ๊ฒฐ ๊ทธ๋ํ
๐ก ์์ ์ ๋ ฅ
9
7 3
7
1 2
1 3
2 7
2 8
2 9
4 5
4 6
→ 7๊ณผ 3์ ๊ด๊ณ๋ ๋ค์๊ณผ ๊ฐ์:
7 → 2 → 1 → 3 → ์ด 3์ด
์์ ์ถ๋ ฅ
3
๐ง ์๊ณ ๋ฆฌ์ฆ ์ ๊ทผ ๋ฐฉ์
- ๊ฐ ์ฌ๋์ ์ ์ ์ผ๋ก ์๊ฐํ๊ณ ์๋ฐฉํฅ ๊ทธ๋ํ ๊ตฌ์ฑ
- DFS๋ก x๋ถํฐ ์์ํด์ y์ ๋๋ฌํ๋ ๊ฒฝ์ฐ๋ฅผ ํ์
- ํ์ ์ค ๋ฐฉ๋ฌธํ ๊น์ด cnt๋ฅผ ํตํด ์ด์๋ฅผ ๊ตฌํจ
๐ ์ ์ฒด ์ฝ๋
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
public class Main {
static List<Integer>[] relation;
static boolean[] checked;
static int res = -1;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
relation = new ArrayList[n+1];
checked = new boolean[n+1];
for(int i = 1; i <= n; i++) {
relation[i] = new ArrayList<>();
}
StringTokenizer st = new StringTokenizer(br.readLine());
int x = Integer.parseInt(st.nextToken());
int y = Integer.parseInt(st.nextToken());
int l = Integer.parseInt(br.readLine());
for(int i = 0; i < l; i++) {
st = new StringTokenizer(br.readLine());
int p = Integer.parseInt(st.nextToken());
int c = Integer.parseInt(st.nextToken());
relation[p].add(c);
relation[c].add(p);
}
dfs(x, y, 0);
System.out.println(res);
}
static void dfs(int start, int end, int cnt) {
if(start == end) {
res = cnt;
return;
}
checked[start] = true;
for(int next : relation[start]) {
if(!checked[next]) {
dfs(next, end, cnt+1);
}
}
}
}
๐ ์ฝ๋ ํด์ค
๊ตฌ๋ฌธ | ์ค๋ช |
relation[p].add(c); relation[c].add(p); | ๋ฌด๋ฐฉํฅ ๊ทธ๋ํ ๊ตฌ์ฑ |
dfs(x, y, 0) | DFS๋ก x๋ถํฐ y๊น์ง ์ด์ ํ์ |
if(start == end) | ๋ชฉ์ ์ง์ ๋๋ฌํ์ ๋ ํ์ฌ ์ด์๋ฅผ ์ ์ฅ |
checked[start] | ๋ฐฉ๋ฌธ ์ฌ๋ถ ์ฒดํฌ๋ก ๋ฌดํ ์ฌ๊ท ๋ฐฉ์ง |
โ ํต์ฌ ํฌ์ธํธ ์์ฝ
- ํธ๋ฆฌ์ฒ๋ผ ๋ณด์ด์ง๋ง ์ค์ ๋ก๋ ์๋ฐฉํฅ ๊ทธ๋ํ ํ์
- DFS๋ฅผ ํตํด ๊ฑฐ๋ฆฌ(=์ด์)๋ฅผ ๋์ ํ๋ฉฐ ํ์
- ๋ ๋ ธ๋๊ฐ ์ฐ๊ฒฐ๋์ง ์์๋ค๋ฉด res๋ -1๋ก ์ ์ง๋จ
'Algorithm & Data Structures > BOJ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
b1002. ํฐ๋ (0) | 2025.05.31 |
---|---|
b17413. ์ด์๊ณ์ฐ (0) | 2025.05.31 |
b1068. ํธ๋ฆฌ (0) | 2025.05.31 |
b9328. ์ด์ (0) | 2025.05.21 |
b10942. ํ ๋ฆฐ๋๋กฌ? (0) | 2025.05.20 |