[백준] 2178번 - 미로탐색

fooooif·2021년 11월 8일
0
post-thumbnail

✍ 문제

문제링크

문제

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개의 정수로 미로가 주어진다. 각각의 수들은 붙어서 입력으로 주어진다.

출력

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

👏 풀이과정

간단한 bfs 문제이다

package dfs_bfs;

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 Baek_2178 {
    static int N;
    static int M;
    static int[][] arr;
    static int[][] dir = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
    static boolean[][] visited;
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        StringTokenizer st = new StringTokenizer(br.readLine());

        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        arr = new int[N][M];
        visited = new boolean[N][M];

        for(int i = 0 ; i < N; i++){
            String a = br.readLine();
            for (int j = 0; j < M; j++) {
                arr[i][j] = Integer.parseInt(a.substring(j, j + 1));
            }
        }

        System.out.println(bfs(0,0));
    }

    static int bfs(int x, int y) {

        Queue<Node> queue = new LinkedList<>();

        queue.add(new Node(x, y, 1));
        visited[0][0] = true;
        while (!queue.isEmpty()) {
            Node poll = queue.poll();
            if (poll.x == arr.length - 1 && poll.y == arr[0].length - 1) {
                return poll.depth;
            }
            for(int i = 0 ; i < dir.length; i++){
                int x_x = poll.x + dir[i][0];
                int y_y = poll.y + dir[i][1];

                if (x_x > -1 && x_x < arr.length && y_y > -1 && y_y < arr[x].length) {
                    if (arr[x_x][y_y] == 1 && visited[x_x][y_y] == false) {
                        visited[x_x][y_y] = true;
                        queue.add(new Node(x_x, y_y, poll.depth + 1));
                    }

                }
            }
        }
        return -1;
    }

    static class Node{

        int x;
        int y;
        int depth;

        Node(int x, int y, int depth) {
            this.x = x;
            this.y= y;
            this.depth = depth;
        }
    }
}



profile
열심히 하자

0개의 댓글