241127 뱀과 사다리 게임

Jongleee·2024년 11월 27일
0

TIL

목록 보기
741/970
public static void main(String[] args) throws IOException {
	BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	int[] board = new int[101];
	boolean[] visited = new boolean[101];
	int[] distance = new int[101];
	Queue<Integer> queue = new LinkedList<>();

	String[] nm = br.readLine().split(" ");
	int ladderCount = Integer.parseInt(nm[0]);
	int snakeCount = Integer.parseInt(nm[1]);

	for (int i = 0; i < ladderCount; i++) {
		String[] ladder = br.readLine().split(" ");
		board[Integer.parseInt(ladder[0])] = Integer.parseInt(ladder[1]);
	}

	for (int i = 0; i < snakeCount; i++) {
		String[] snake = br.readLine().split(" ");
		board[Integer.parseInt(snake[0])] = Integer.parseInt(snake[1]);
	}

	queue.offer(1);
	visited[1] = true;

	while (!queue.isEmpty()) {
		int current = queue.poll();
		if (current == 100) {
			System.out.println(distance[current]);
			return;
		}
		for (int dice = 1; dice <= 6; dice++) {
			int next = current + dice;
			if (next > 100) continue;
			if (board[next] != 0) next = board[next];
			if (!visited[next]) {
				visited[next] = true;
				distance[next] = distance[current] + 1;
				queue.offer(next);
			}
		}
	}
}

출처:https://www.acmicpc.net/problem/16928

0개의 댓글