문제

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

 

출력

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


코드

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

public class Main {
    static class Node {
        int x;
        int y;
        int cnt; // 현재까지 이동한 칸 수

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

    static int[][] maze;
    static boolean[][] visited;
    static int N;
    static int M;
    static int moveCnt;
    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());

        maze = new int[N+1][M+1];
        visited = new boolean[N+1][M+1];

        for(int i = 0; i < N; i++){
            String str = br.readLine();

            for(int j = 0; j < M; j++){
                maze[i+1][j+1] = str.charAt(j) - '0';
            }
        }

        bfs();

        System.out.println(moveCnt);

    }


    static void bfs(){
        // 상 하 좌 우
        int[] dx = new int[]{0,0,-1,1};
        int[] dy = new int[]{-1,1,0,0};

        Queue<Node> queue = new LinkedList<>();
        queue.add(new Node(1,1,1));
        visited[1][1] = true;

        while(!queue.isEmpty()){
            Node node = queue.poll();

            for(int i = 0; i < 4; i++){
                int nx = node.x + dx[i];
                int ny = node.y + dy[i];

                if(checkBoundary(nx, ny)){
                    if(nx == N && ny == M) {
                        moveCnt = node.cnt + 1;
                        return;
                    }
                    visited[nx][ny] = true;
                    queue.add(new Node(nx, ny, node.cnt + 1));
                }
            }
        }
    }

    static boolean checkBoundary(int nx, int ny){
        return nx >= 1 && nx <= N && ny >= 1 && ny <= M && maze[nx][ny] == 1 && !visited[nx][ny];
    }
}

BFS를 이용해서 풀었다. visited 배열을 이용해서 방문 여부를 저장하고, queue에 출발하는 칸인 (1,1)을 넣었다. 이때, Node class를 생성하여 넣어주었는데, x좌표, y좌표, 현재까지 이동한 총 cnt를 저장하고 있는 객체이다. queue가 빌 때까지 queue에서 객체를 하나 뽑고, 해당 객체의 상, 하, 좌, 우에 있는 값을 큐에 넣어준다. 이동할 때는 미로의 경계값을 넘지 않는지와 처음 방문하는 곳인지를 확인하고, 큐에 Node를 넣을 때는 cnt를 하나씩 올려서 넣어준다. 원하는 값은 x가 N이고, y가 M일 때이기 때문에, 다음에 방문할 x와 y인 nx, ny 값을 확인하여 nx가 N이고 ny가 M일 때 최소 이동 칸 수를 저장하는 moveCnt에 값을 저장해주고 return 한다.

728x90

'Algorithm > 백준' 카테고리의 다른 글

[백준][Java] 2493. 탑  (0) 2024.08.13
[백준][Java] 1021. 회전하는 큐  (0) 2024.08.10
[백준][Java] 1920. 수 찾기  (0) 2024.02.11
[백준][Java] 2630. 색종이 만들기  (0) 2024.02.06
[백준][Java] 14888. 연산자 끼워넣기  (0) 2024.02.05

+ Recent posts