미로 탐색

Huisu·2023년 10월 10일
0

Coding Test Practice

목록 보기
42/98
post-thumbnail

문제

2178번: 미로 탐색

문제 설명

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

101111
101010
101011
111011

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

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

제한 사항

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

입출력 예

입력출력
4 6
101111
101010
101011
11101115
4 6
110110
110110
111111
1111019
2 25
1011101110111011101110111
111011101110111011101110138
7 7
1011111
1110001
1000001
1000001
1000001
1000001
111111113

입출력 예 설명

아이디어

BFS

거리를 조사할 때 int distance로 두면 조사하는 모든 범위가 카운팅돼서 안 좋음 (단일 경로가 있는 것 아닌 이상)

따라서 distance[][]로 기록해 둔 다음에 목적지를 출력하는 게 낫다

제출 코드


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

public class one2178 {
    public static int[][] map;
    public static boolean[][] visited;
    public static int[][] distance;
    public static int[] dRow = {0, 0, -1, 1};
    public static int[] dCol = {1, -1, 0, 0};
    public void solution() throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer infoToken = new StringTokenizer(reader.readLine());
        int n = Integer.parseInt(infoToken.nextToken());
        int m = Integer.parseInt(infoToken.nextToken());

        map = new int[n][m];
        visited = new boolean[n][m];
        distance = new int[n][m];

        for (int i = 0; i < n; i++) {
            String mapInfo = reader.readLine();
            for (int j = 0; j < m; j++) {
                map[i][j] = Integer.parseInt(String.valueOf(mapInfo.charAt(j)));
            }
        }

        Queue<int[]> toVisit = new LinkedList<>();
        toVisit.add(new int[] {0, 0});
        visited[0][0] = true;
        distance[0][0] = 1;

        while(!toVisit.isEmpty()) {
            int[] now = toVisit.poll();
            int nowCol = now[0];
            int nowRow = now[1];

            if (nowCol == n - 1 && nowRow == m - 1) break;

            for (int i = 0; i < 4; i++) {
                int nextCol = nowCol + dCol[i];
                int nextRow = nowRow + dRow[i];

                if (nextCol < 0 || nextCol >= n || nextRow < 0 || nextRow >= m) continue;
                if (visited[nextCol][nextRow]) continue;
                if (map[nextCol][nextRow] == 0) continue;

                visited[nextCol][nextRow] = true;
                toVisit.add(new int[] {nextCol, nextRow});
                distance[nextCol][nextRow] = distance[nowCol][nowRow] + 1;
            }
        }

        System.out.println(distance[n - 1][m - 1]);
    }

    public static void main(String[] args) throws IOException {
        new one2178().solution();
    }
}

0개의 댓글