티스토리 뷰

coding test/백준

[BOJ]2644_촌수계산

아풀 2018. 7. 16. 23:46

문제_2644

>> 코드

import java.io.*;
import java.util.*;

public class boj_2644 {

	static int n;
	static int[][] people;
	static int[] d;
	static boolean[] visit;
	
	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub

		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		n = Integer.parseInt(br.readLine());
		people = new int[n][n];
		d = new int[n];
		visit = new boolean[n];
		
		StringTokenizer st = new StringTokenizer(br.readLine());

		int qA = Integer.parseInt(st.nextToken());
		int qB = Integer.parseInt(st.nextToken());
		
		int m = Integer.parseInt(br.readLine());
		
		for(int i = 0 ; i < m ; i++) {
			st = new StringTokenizer(br.readLine());

			int parent = Integer.parseInt(st.nextToken())-1;
			int child = Integer.parseInt(st.nextToken())-1;
			
			people[parent][child] = people[child][parent] = 1;
		}
		
		int answer = chon(qA-1, qB-1);
		System.out.println(answer == 0 ? -1 : answer);
		
	}
	
	static int chon(int qA, int qB) {
		Queue q = new LinkedList();
		
		q.add(qA);
		d[qA] = 0;
		visit[qA] = true;
		
		while(!q.isEmpty()) {
			int tempParent = q.poll();
			int tempChild = d[tempParent];
			
			for(int i = 0 ; i < n ; i ++) {
				if(!visit[i] && people[tempParent][i] == 1) {
					visit[i] = true;
					q.add(i);
					d[i] = tempChild+1;
				}
			}
		}
		return d[qB];
	}
}

>> 해설


https://www.acmicpc.net/problem/2644

'coding test > 백준' 카테고리의 다른 글

[BOJ]2579_계단 오르기  (0) 2018.07.18
[BOJ]2589_보물섬  (0) 2018.07.17
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
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
글 보관함