코딩테스트/백준문제

[Java] 백준_16928_뱀과 사다리 게임

jaewon_sss 2021. 7. 10. 13:43
반응형

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

 

16928번: 뱀과 사다리 게임

첫째 줄에 게임판에 있는 사다리의 수 N(1 ≤ N ≤ 15)과 뱀의 수 M(1 ≤ M ≤ 15)이 주어진다. 둘째 줄부터 N개의 줄에는 사다리의 정보를 의미하는 x, y (x < y)가 주어진다. x번 칸에 도착하면, y번 칸으

www.acmicpc.net

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

public class Main {

	static BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
	static StringTokenizer tokens;
	static StringBuilder output = new StringBuilder();
	static int N, M, cnt;
	static int[] map = new int[101];
	static boolean[] visited = new boolean[101];

	public static void main(String args[]) throws Exception {
		tokens = new StringTokenizer(input.readLine());
		N = Integer.parseInt(tokens.nextToken());
		M = Integer.parseInt(tokens.nextToken());
		for (int n = 0; n < N + M; n++) {
			tokens = new StringTokenizer(input.readLine());
			map[Integer.parseInt(tokens.nextToken())] = Integer.parseInt(tokens.nextToken());
		}
		bfs(1);
		System.out.println(cnt);
	}

	private static void bfs(int i) {
		Queue<Integer> queue = new LinkedList<>();
		queue.offer(i);
		visited[i] = true;
		while (!queue.isEmpty()) {
			int size = queue.size();
			while (size-- > 0) {
				int start = queue.poll();
				if(start == 100) return;
				for (int k = 1; k < 7; k++) {
					int next = start + k;
					if(next <= 100 && !visited[next]) {
						//들어와서
						
						//1. 뱀, 사다리가 있을경우
						if(map[next] != 0) {
							next = map[next];
							if(visited[next]) continue;
						}
						//2. 없을경우
						queue.offer(next);
						visited[next]=true;
					}
					
				}
			}
			cnt++;
		}

	}
}

 

반응형