Baekjoon

[백준2178] 미로 탐색 / Java

개발하는 사막여우 2020. 12. 29. 10:01
반응형

TITLE

문제주소 : www.acmicpc.net/problem/2178

 


<문제 설명>

N×M크기의 배열로 표현되는 미로가 있다.

1 0 1 1 1 1
1 0 1 0 1 0
1 0 1 0 1 1
1 1 1 0 1 1

미로에서 1은 이동할 수 있는 칸을 나타내고, 0은 이동할 수 없는 칸을 나타낸다. 이러한 미로가 주어졌을 때, (1, 1)에서 출발하여 (N, M)의 위치로 이동할 때 지나야 하는 최소의 칸 수를 구하는 프로그램을 작성하시오. 한 칸에서 다른 칸으로 이동할 때, 서로 인접한 칸으로만 이동할 수 있다.

위의 예에서는 15칸을 지나야 (N, M)의 위치로 이동할 수 있다. 칸을 셀 때에는 시작 위치와 도착 위치도 포함한다.

입력

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 N개의 줄에는 M개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

출력

첫째 줄에 지나야 하는 최소의 칸 수를 출력한다. 항상 도착위치로 이동할 수 있는 경우만 입력으로 주어진다.

예제 입력 

4 6
101111
101010
101011
111011

예제 출력

15

<풀이법>

▒ 한줄 개념: BFS  

그래프 상에서 어떤 정점으로부터 나머지 정점으로의 최단거리는 BFS로 구할 수 있습니다.

기존의 BFS 풀이방식에 거리를 나타내는 배열 distance를 추가하면 간단히 구현할 수 있습니다.

 

<코드(Java)>


import java.util.Scanner;
import java.util.LinkedList;

public class Maze_Navigation_2178 {
    public static void main(String[] args){

        Scanner sc = new Scanner(System.in);
        int[][] matrix = new int[sc.nextInt()][sc.nextInt()];
        for(int i = 0; i< matrix.length;i++){
            String line = sc.next();
            for(int j = 0; j < line.length(); j++){
                matrix[i][j] = Character.getNumericValue(line.charAt(j));
            }
        }
        search(matrix);
    }

    static void search(int[][] matrix){
        int[][] CHECK_POSITION = {{-1,0}, {0,1}, {1,0}, {0,-1}};
        int N = matrix.length;
        int M = matrix[0].length;
        int[][] distance = new int[N][M];
        boolean[][] visited = new boolean[N][M];
        LinkedList<int[]> queue = new LinkedList<>();

        queue.add(new int[]{0,0});
        distance[0][0] = 1;
        while(!queue.isEmpty()){
            int[] cur_position = queue.poll();
            int x = cur_position[0];
            int y = cur_position[1];
            if(x == N-1 && y == M-1){
                System.out.println(distance[x][y]);
                break;
            }
            for(int[] position: CHECK_POSITION){
                int new_x = x+position[0];
                int new_y = y+position[1];
                if(new_x >= 0 && new_y >= 0 && new_x < N && new_y < M){
                    if(matrix[new_x][new_y] == 1) {
                        if (!visited[new_x][new_y]) {
                            visited[new_x][new_y] = true;
                            distance[new_x][new_y] = distance[x][y] + 1;
                            queue.add(new int[]{new_x, new_y});
                        } else if (distance[new_x][new_y] > distance[x][y] + 1){
                            distance[new_x][new_y] = distance[x][y] + 1;
                            queue.add(new int[]{new_x, new_y});
                        }
                    }
                }
            }
        }
    }
}

 

 

더 많은 코드 보기(GitHub) : github.com/dwkim-97/CodingTest

 

 

반응형