https://www.acmicpc.net/problem/2644
2644번: 촌수계산
사람들은 1, 2, 3, …, n (1 ≤ n ≤ 100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어
www.acmicpc.net
백준_2644번_촌수계산 문제는 bfs,dfs로 모두 풀 수 있는 그래프 문제이며,
개인적으로 더 편한 bfs로 풀이하였습니다.
import java.util.*;
import java.io.*;
public class Main {
static int start,end,n;
static int[][] graph;
static int[] dist;
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
dist = new int[n+1];
graph = new int[n+1][n+1];
StringTokenizer st = new StringTokenizer(br.readLine());
start = Integer.parseInt(st.nextToken());
end = Integer.parseInt(st.nextToken());
int line = Integer.parseInt(br.readLine());
for (int i = 0; i < line; i++) {
st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
graph[a][b] = graph[b][a] = 1;
}
bfs(start);
System.out.println(dist[end] == 0? -1:dist[end]);
}
private static void bfs(int x) {
Queue<Integer> q = new LinkedList<>();
q.add(x);
while (!q.isEmpty()){
int nx = q.poll();
for (int i = 0; i <=n; i++) {
if(graph[nx][i] == 1 && dist[i]==0){
q.add(i);
dist[i] = dist[nx]+1;
}
}
}
}
}
'CodingTest' 카테고리의 다른 글
백준_11724번_연결 요소의 개수_자바 (0) | 2024.01.18 |
---|---|
백준_11659번_구간 합 구하기 4_자바 (2) | 2024.01.16 |
백준_2839_설탕 배달_자바 (1) | 2024.01.05 |
백준_1018번_체스판 다시 칠하기_자바 (2) | 2024.01.04 |
코딩테스트 기본 유형 정리 (1) | 2024.01.01 |