티스토리 뷰

카테고리 없음

[BAEKJOON] 2644 촌수계산

응애~ 개발자 2024. 11. 4. 23:43
728x90
반응형

문제 요약

문제풀이

 

Code

Python

 

Java

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class Main {


	public static void main(String[] args) throws IOException {

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		Map<Integer, List<Integer>> adj = new HashMap<>();
		int N = Integer.parseInt(br.readLine());

		for (int i = 1; i <= N; i++) {
			adj.put(i, new ArrayList<>());
		}

		StringTokenizer st = new StringTokenizer(br.readLine());
		int from = Integer.parseInt(st.nextToken());
		int to = Integer.parseInt(st.nextToken());
		int count = Integer.parseInt(br.readLine());

		for (int i = 0; i <  count; i++) {
			st = new StringTokenizer(br.readLine());
			int a = Integer.parseInt(st.nextToken());
			int b = Integer.parseInt(st.nextToken());
			adj.get(a).add(b);
			adj.get(b).add(a);
		}

		int[] visited = new int[N + 1];
		Arrays.fill(visited, -1);

		Stack<Integer> stack = new Stack<>();
		stack.add(from);
		visited[from] = 0;

		while (!stack.empty()){
			int now = stack.pop();
			for(Integer node : adj.get(now)){
				if(visited[node] == -1){
					visited[node] = visited[now] + 1;
					stack.add(node);
				}
			}
		}

		System.out.println(visited[to]);

	}
}
728x90
반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2025/01   »
1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30 31
글 보관함