1. 오늘의 문제 - 촌수 계산 - 백준 : 2644번
https://www.acmicpc.net/problem/2644
2. 문제 풀이 전략
DFS로 그래프 탐색을 하면 될 것 같고,
양방향 그래프이고,
사람들이 100명뿐이 안되니까 인접행렬 사용하면 될 것 같다.
3. 풀이
package io.conduktor.demos.dfsbfs.hanghaecote99.middler;
import java.io.*;
import java.util.StringTokenizer;
// 8. 촌수 계산 - 백준 : 2644 - DFS, BFS
public class ChonNumber8 {
static int N;
static int targetA;
static int targetB;
static int M;
static int answer = 0;
static int[][] adjMatrix;
static int[] ch;
static void dfs(int idx, int count) {
ch[idx] = 1;
if (idx == targetB) answer = count;
for (int i = 1; i <= N; i++) {
if (adjMatrix[idx][i] == 1 && ch[i] == 0) {
dfs(i, count + 1);
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
StringTokenizer st;
N = Integer.parseInt(br.readLine());
st = new StringTokenizer(br.readLine());
targetA = Integer.parseInt(st.nextToken());
targetB = Integer.parseInt(st.nextToken());
M = Integer.parseInt(br.readLine());
adjMatrix = new int[N+1][N+1];
for (int i = 0; i < M; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
adjMatrix[a][b] = 1;
adjMatrix[b][a] = 1;
}
ch = new int[N+1];
answer = -1;
dfs(targetA, 0);
bw.write(answer + "\n");
bw.flush();
bw.close();
br.close();
}
}
4. 소감
힘을 내자
'코딩테스트' 카테고리의 다른 글
특정 거리의 도시 찾기 - 백준 18352 - Java - 다익스트라 (0) | 2024.11.28 |
---|---|
이중 우선순위 큐 - Heap - 프로그래머스 - Java (0) | 2024.11.23 |
99클럽 코테 스터디 Java 미들러 7일차 TIL - 모음 사전 : 프로그래머스 (Level 2) - DFS (0) | 2024.11.03 |
99클럽 코테 스터디 Java 미들러 6일차 TIL - 나무 자르기 : 백준 2805번 - 이분탐색 (0) | 2024.11.02 |
99클럽 코테 스터디 Java 5일차 TIL - 알고리즘 수업 - 너비 우선 탐색 1 : 백준 24444번 - BFS (0) | 2024.11.01 |