벽 부수고 이동하기 2

Updated:


import java.io.IOException;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
	static int[][] arr;
	static int N;
	static int M;
	static int K;

	public static void main(String[] args) throws IOException {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);

		N = sc.nextInt();
		M = sc.nextInt();
		K = sc.nextInt();

		arr = new int[N][M];
		int[][] tmp = new int[N][M];

		int cnt = 0;
		for (int i = 0; i < N; i++) {
			String str = sc.next();
			for (int j = 0; j < M; j++) {
				tmp[i][j] = Integer.MAX_VALUE;
				if (str.charAt(j) == '1')
					arr[i][j] = 1;
				else
					arr[i][j] = 0;
			}
		}

		Queue<Node> q = new LinkedList<>();
		boolean[][][] che = new boolean[K + 1][N][M];

		q.add(new Node(0, 0, 1, 0));
		che[0][0][0] = true;
		boolean re = false;
		while (!q.isEmpty()) {
			Node node = q.poll();
			if (node.r == N - 1 && node.c == M - 1) {
				System.out.print(node.cnt);
				re = true;
				break;
			}
			for (int i = 0; i < 4; i++) {
				int nr = node.r + dr[i];
				int nc = node.c + dc[i];
				if (nr >= 0 && nc >= 0 && nr < N && nc < M) {
					if (arr[nr][nc] == 1 && node.che < K && !che[node.che + 1][nr][nc]) {
						tmp[nr][nc] = node.cnt + 1;
						che[node.che + 1][nr][nc] = true;
						q.add(new Node(nr, nc, node.cnt + 1, node.che + 1));
					}
					if (arr[nr][nc] == 0 && !che[node.che][nr][nc]) {
						tmp[nr][nc] = node.cnt + 1;
						che[node.che][nr][nc] = true;
						q.add(new Node(nr, nc, node.cnt + 1, node.che));
					}
				}
			}
		}

		/*
		 * for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) {
		 * System.out.print(tmp[i][j] + " \t"); } System.out.println(); }
		 */

		if (!re)
			System.out.println(-1);
	}

	static int[] dr = { 1, 0, -1, 0 };
	static int[] dc = { 0, 1, 0, -1 };

	static class Node {
		int r, c, cnt, che;

		Node(int r, int c, int cnt, int che) {
			this.r = r;
			this.c = c;
			this.cnt = cnt;
			this.che = che;
		}
	}

}

문제

N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 당신은 (1, 1)에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로로 이동하려 한다. 최단경로는 맵에서 가장 적은 개수의 칸을 지나는 경로를 말하는데, 이때 시작하는 칸과 끝나는 칸도 포함해서 센다.

만약에 이동하는 도중에 벽을 부수고 이동하는 것이 좀 더 경로가 짧아진다면, 벽을 K개 까지 부수고 이동하여도 된다.

맵이 주어졌을 때, 최단 경로를 구해 내는 프로그램을 작성하시오.

입력

첫째 줄에 N(1 ≤ N ≤ 1,000), M(1 ≤ M ≤ 1,000), K(1 ≤ K ≤ 10)이 주어진다. 다음 N개의 줄에 M개의 숫자로 맵이 주어진다. (1, 1)과 (N, M)은 항상 0이라고 가정하자.

출력

첫째 줄에 최단 거리를 출력한다. 불가능할 때는 -1을 출력한다.

예제 입력 1

6 4 1
0100
1110
1000
0000
0111
0000

예제 출력 1

15

예제 입력 2

6 4 2
0100
1110
1000
0000
0111
0000

예제 출력 2

9

예제 입력 3

4 4 3
0111
1111
1111
1110

예제 출력 3

-1

Leave a comment