본문 바로가기

알고리즘/초급1

[JAVA] 백준 1261번: 알고스팟 ( 초급 2-53 ) - hard

문제

알고스팟 운영진이 모두 미로에 갇혔다. 미로는 N*M 크기이며, 총 1*1크기의 방으로 이루어져 있다. 미로는 빈 방 또는 벽으로 이루어져 있고, 빈 방은 자유롭게 다닐 수 있지만, 벽은 부수지 않으면 이동할 수 없다.

알고스팟 운영진은 여러명이지만, 항상 모두 같은 방에 있어야 한다. 즉, 여러 명이 다른 방에 있을 수는 없다. 어떤 방에서 이동할 수 있는 방은 상하좌우로 인접한 빈 방이다. 즉, 현재 운영진이 (x, y)에 있을 때, 이동할 수 있는 방은 (x+1, y), (x, y+1), (x-1, y), (x, y-1) 이다. 단, 미로의 밖으로 이동 할 수는 없다.

벽은 평소에는 이동할 수 없지만, 알고스팟의 무기 AOJ를 이용해 벽을 부수어 버릴 수 있다. 벽을 부수면, 빈 방과 동일한 방으로 변한다.

만약 이 문제가 알고스팟에 있다면, 운영진들은 궁극의 무기 sudo를 이용해 벽을 한 번에 다 없애버릴 수 있지만, 안타깝게도 이 문제는 Baekjoon Online Judge에 수록되어 있기 때문에, sudo를 사용할 수 없다.

현재 (1, 1)에 있는 알고스팟 운영진이 (N, M)으로 이동하려면 벽을 최소 몇 개 부수어야 하는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 미로의 크기를 나타내는 가로 크기 M, 세로 크기 N (1 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 미로의 상태를 나타내는 숫자 0과 1이 주어진다. 0은 빈 방을 의미하고, 1은 벽을 의미한다.

(1, 1)과 (N, M)은 항상 뚫려있다.

출력

첫째 줄에 알고스팟 운영진이 (N, M)으로 이동하기 위해 벽을 최소 몇 개 부수어야 하는지 출력한다.

 

문제 풀이

모든 case를 다 살펴보고, 결과를 프린트하는 형식이다.

 

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

public class baekjoon1261_2 {
    private static int row;
    private static int col;
    private static int[][] info;
    private static int[][] distInfo;
    private static boolean[][] visit;
    private static int[] rowTemp = { -1, 1, 0, 0 };
    private static int[] colTemp = { 0, 0, -1, 1 };

    public static void main(String[] args) throws IOException {
        // 3 3
        // 011
        // 111
        // 110
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        col = Integer.parseInt(st.nextToken());
        row = Integer.parseInt(st.nextToken());
        info = new int[row][col];
        distInfo = new int[row][col];
        visit = new boolean[row][col];

        for (int i = 0; i < row; i++) {
            String temp = br.readLine();
            for (int j = 0; j < col; j++) {
                info[i][j] = Character.getNumericValue(temp.charAt(j));
                // distInfo[i][j] = -1;
            }
        }

        bfs1261();
        System.out.println(distInfo[row - 1][col - 1]);

    }

    private static void bfs1261() {
        Queue<Position1261> queue = new LinkedList<>();
        queue.add(new Position1261(0, 0));

        while (!queue.isEmpty()) {
            Position1261 currentPosition = queue.remove();
            int currentRow = currentPosition.row;
            int currentCol = currentPosition.col;

            for (int i = 0; i < 4; i++) {
                int nextRow = currentRow + rowTemp[i];
                int nextCol = currentCol + colTemp[i];

                if (nextRow >= 0 && nextCol >= 0 && nextCol < col && nextRow < row) {
                    if (info[nextRow][nextCol] == 1) {
                        if (distInfo[nextRow][nextCol] > distInfo[currentRow][currentCol] + 1
                                || !visit[nextRow][nextCol]) {
                            visit[nextRow][nextCol] = true;
                            distInfo[nextRow][nextCol] = distInfo[currentRow][currentCol] + 1;
                            queue.add(new Position1261(nextRow, nextCol));
                        }
                    }
                    if (info[nextRow][nextCol] == 0) {
                        if (distInfo[nextRow][nextCol] > distInfo[currentRow][currentCol] || !visit[nextRow][nextCol]) {
                            visit[nextRow][nextCol] = true;
                            distInfo[nextRow][nextCol] = distInfo[currentRow][currentCol];
                            queue.add(new Position1261(nextRow, nextCol));
                        }
                    }
                }
            }

        }
    }
}

class Position1261 {
    int row;
    int col;

    public Position1261(int row, int col) {
        this.row = row;
        this.col = col;
    }
}

 

덱을 사용해서 해결하는 형식이다.

위 코드보다 조금 더 효율적이라고 할 수 있겠다.

 

import java.util.ArrayDeque;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int m = sc.nextInt();
        int n = sc.nextInt();
        int[] aryH = { 0, 0, -1, 1 };
        int[] aryW = { 1, -1, 0, 0 };
        int[][] info = new int[n][m];
        boolean[][] visit = new boolean[n][m];
        int[][] dist = new int[n][m];

        ArrayDeque<int[]> dq = new ArrayDeque<>();
        for (int i = 0; i < n; i++) {
            String temp = sc.next();
            for (int j = 0; j < m; j++) {
                info[i][j] = temp.charAt(j) - '0';
            }
        }
        dq.addFirst(new int[] { 0, 0 });
        visit[0][0] = true;

        while (!dq.isEmpty()) {
            int[] position = dq.removeFirst();
            int h = position[0];
            int w = position[1];
            if (h == n && w == m) {
                break;
            }
            for (int i = 0; i < 4; i++) {
                int newH = h + aryH[i];
                int newW = w + aryW[i];
                if (0 <= newW && 0 <= newH && newH < n && newW < m && !visit[newH][newW]) {

                    visit[newH][newW] = true;
                    if (info[newH][newW] == 1) {
                        dq.addLast(new int[] { newH, newW });
                        dist[newH][newW] = dist[h][w] + 1;
                    } else if (info[newH][newW] == 0) {

                        dq.addFirst(new int[] { newH, newW });
                        dist[newH][newW] = dist[h][w];
                    }
                }
            }
        }
        System.out.println(dist[n - 1][m - 1]);
    }
}