본문 바로가기

알고리즘/BOJ

2644. 촌수계산

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

 

2644번: 촌수계산

사람들은 1, 2, 3, …, n (1≤n≤100)의 연속된 번호로 각각 표시된다. 입력 파일의 첫째 줄에는 전체 사람의 수 n이 주어지고, 둘째 줄에는 촌수를 계산해야 하는 서로 다른 두 사람의 번호가 주어진다. 그리고 셋째 줄에는 부모 자식들 간의 관계의 개수 m이 주어진다. 넷째 줄부터는 부모 자식간의 관계를 나타내는 두 번호 x,y가 각 줄에 나온다. 이때 앞에 나오는 번호 x는 뒤에 나오는 정수 y의 부모 번호를 나타낸다. 각 사람의 부모는 최대

www.acmicpc.net

<JAVA>

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

class Main {
	static int n, m;
	static int num1, num2;
	static int x, y;
	static int depth[] = new int[101];
	static int map[][] = new int[101][101];
	static boolean visit[] = new boolean[101];
	static Queue<Integer> q = new LinkedList<>();

	public static void main(String[] args) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st;
		n = Integer.parseInt(br.readLine());
		st = new StringTokenizer(br.readLine(), " ");
		num1 = Integer.parseInt(st.nextToken(" "));
		num2 = Integer.parseInt(st.nextToken(" "));
		m = Integer.parseInt(br.readLine());
		int a, b;
		for (int i = 1; i <= m; i++) {
			st = new StringTokenizer(br.readLine(), " ");
			a = Integer.parseInt(st.nextToken(" "));
			b = Integer.parseInt(st.nextToken(" "));
			map[a][b] = 1;
			map[b][a] = 1;
		}
		visit[num1] = true;
		q.add(num1);
		int temp;
		while (!q.isEmpty()) {
			temp = q.poll();
			for (int i = 1; i <= n; ++i) {
				if (map[temp][i] == 1 && !visit[i]) {
					visit[i] = true;
					depth[i] = depth[temp] + 1;
					q.add(i);
				}
			}
		}
		if (depth[num2] != 0)
			System.out.println(depth[num2]);
		else
			System.out.println("-1");
	}
}

<C++>

#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
int n, m;
int num1, num2;
int x, y;
int depth[101];
int map[101][101];
bool visit[101];
queue <int> q;
int main()
{
	cin.tie(NULL); cout.tie(NULL); ios_base::sync_with_stdio(false);
	cin >> n;
	cin >> num1 >> num2;
	cin >> m;
	int a, b;
	for (int i = 1; i <= m; i++)
	{
		cin >> a >> b;
		map[a][b] = 1;
		map[b][a] = 1;
	}
	visit[num1] = true;
	q.push(num1);
	int temp;
	while (!q.empty())
	{
		temp = q.front(); q.pop();
		for (int i = 1; i <= n; ++i)
		{
			if (map[temp][i] == 1 && !visit[i])
			{
				visit[i] = true;
				depth[i] = depth[temp] + 1;
				q.push(i);
			}
		}
	}
	if (depth[num2] != 0)
		cout << depth[num2] << "\n";
	else
		cout << "-1\n";
	return 0;
}

'알고리즘 > BOJ' 카테고리의 다른 글

17472. 다리 만들기 2  (0) 2019.10.16
16234. 인구 이동  (0) 2019.10.16
10026. 적록색약  (0) 2019.10.15
14889. 스타트와 링크  (0) 2019.10.15
16235. 나무재테크  (0) 2019.10.15