JuSeok

1987번

문제

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

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

한 칸에서 이동할 수 있는 칸은 상하좌우로 인접한 칸이다.

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

문제 해결 순서

  1. 처음엔 손에 익은 dfs(깊이 우선 탐색으로 풀었다.)
  2. 벽을 부셨을 때를 boolean으로 넘겨줘서 탐색하는 방식을 썼다.
  3. 결과는 시간초과... 최악의 경우를 못 피한다는 뜻인데 이 부분이 이해가 안된다.
  4. 2차로 시도한 것이 bfs(넓이 우선 탐색.)
  5. 여러 예제들을 넣고 테스트를 해보니 벽이 없이 모두 0으로 맵이 이뤄져있을 때 dfs는 시간이 말도 안되게 오래 걸리더라. (코드가 이상했을 수도)
  6. 똑같은 원리로 bfs로 작성하니 통과했다.

dfs로 푼 코드

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

class Main {
   static int n, m;
   static String arr[][];
   static boolean visit[][];
   static int answer = Integer.MAX_VALUE;
   public static void main(String[] args) throws IOException {
       long startTime = System.currentTimeMillis();
       Scanner scanner = new Scanner(System.in);
       n = scanner.nextInt();
       m = scanner.nextInt();
       arr = new String[n][m];
       visit = new boolean[n][m];
       scanner.nextLine();
       for (int i = 0; i < n; i++){
           arr[i] = scanner.nextLine().split("");
       }

       dfs(0, 0, false, 0);
       if (answer != Integer.MAX_VALUE){
           System.out.println(answer + 1);
       }
       else{
           System.out.println(-1);
       }

       long estimatedTime = System.currentTimeMillis() - startTime;

       System.out.println(estimatedTime);
   }

   static void dfs(int x, int y, boolean wall, int count){
       // 방문
       visit[x][y] = true;

       // 정답인 경우
       if (x == n - 1 && y == m - 1){
           answer = Math.min(answer, count);
       }
       else{
           // 상하좌우
           if (x > 0 && !visit[x - 1][y]){
               if (arr[x - 1][y].equals("1") && !wall){
                   dfs(x - 1, y, true, count + 1);
               }
               if(arr[x - 1][y].equals("0")){
                   dfs(x - 1, y, wall, count + 1);
               }
           }
           if (x < n - 1 && !visit[x + 1][y]){
               if (arr[x + 1][y].equals("1") && !wall){
                   dfs(x + 1, y, true, count + 1);
               }
               if(arr[x + 1][y].equals("0")){
                   dfs(x + 1, y, wall, count + 1);
               }
           }
           if (y > 0 && !visit[x][y - 1]){
               if (arr[x][y - 1].equals("1") && !wall){
                   dfs(x, y - 1, true, count + 1);
               }
               if(arr[x][y - 1].equals("0")){
                   dfs(x, y - 1, wall, count + 1);
               }
           }
           if (y < m - 1 && !visit[x][y + 1]){
               if (arr[x][y + 1].equals("1") && !wall){
                   dfs(x, y + 1, true, count + 1);
               }
               if(arr[x][y + 1].equals("0")){
                   dfs(x, y + 1, wall, count + 1);
               }
           }
       }
       visit[x][y] = false;
   }
}

bfs로 푼 코드



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

class Main {
    public static int N, M, ans = Integer.MAX_VALUE;
    public static int[] dirX = new int[] { 0, 0, -1, 1 };
    public static int[] dirY = new int[] { -1, 1, 0, 0 };
    public static int[][] map;
    public static boolean[][][] visited;

    public static void main(String[] args) throws Exception {
        long startTime = System.currentTimeMillis();


        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        map = new int[N][M];
        visited = new boolean[2][N][M];

        for (int i = 0; i < N; i++) {
            String str = br.readLine();
            for (int j = 0; j < M; j++) {
                map[i][j] = Integer.parseInt(str.charAt(j) + "");
            }
        }
        solve();
        if(ans == Integer.MAX_VALUE)
            System.out.println(-1);
        else
            System.out.println(ans);

        long estimatedTime = System.currentTimeMillis() - startTime;

        System.out.println(estimatedTime);
    }

    public static void solve() {

        Queue<Node> q = new LinkedList<Node>();
        q.offer(new Node(0, 0, 1, 0));

        while (!q.isEmpty()) {

            Node node = q.poll();
            int row = node.row;
            int col = node.col;
            int cnt = node.cnt;
            int jump = node.jump;

            // 목표 지점에 도달 했는지
            if (row == N - 1 && col == M - 1) {
                ans = Math.min(ans, cnt);
                continue;
            }

            for (int i = 0; i < 4; i++) {
                int nr = row + dirX[i];
                int nc = col + dirY[i];

                if (isBoundary(nr, nc)) {
                    if (jump == 1) {

                        if (!visited[jump][nr][nc] && map[nr][nc] == 0) {
                            visited[jump][nr][nc] = true;
                            q.offer(new Node(nr, nc, cnt + 1, jump));
                        }

                    } else { // 벽을 안부순 상태

                        if (map[nr][nc] == 1) {
                            if (!visited[jump + 1][nr][nc]) {
                                visited[jump + 1][nr][nc] = true;
                                q.offer(new Node(nr, nc, cnt + 1, jump + 1));
                            }
                        } else if (map[nr][nc] == 0) {
                            if (!visited[jump][nr][nc]) {
                                visited[jump][nr][nc] = true;
                                q.offer(new Node(nr, nc, cnt + 1, jump));
                            }
                        }
                    }
                }
            }
        }
    }

    public static boolean isBoundary(int row, int col) {
        return (row >= 0 && row < N) && (col >= 0 && col < M);
    }
}

class Node {

    int row;
    int col;
    int cnt;
    int jump;

    public Node(int row, int col, int cnt, int jump) {
        super();
        this.row = row;
        this.col = col;
        this.cnt = cnt;
        this.jump = jump;
    }

}

Tags