[백준]2178번 미로 탐색

Yeeun_Kim·2023년 11월 3일
0
post-thumbnail

문제풀이(JAVA)

import java.io.*;
import java.util.*;

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

public class Main {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(br.readLine());

        int n = Integer.parseInt(st.nextToken());
        int m = Integer.parseInt(st.nextToken());

        int[][] maze = new int[n][m];

        for(int i = 0; i<n; i++) {
            maze[i] = Arrays.stream(br.readLine().split("")).mapToInt(Integer::parseInt).toArray();
        }

        escapeMaze(maze);
    }

    public static void escapeMaze(int[][] maze) {
        boolean[][] visited = new boolean[maze.length][maze[0].length];

        int[] dx = {0,0,1,-1};
        int[] dy = {1,-1,0,0};

        Queue<Position> queue = new LinkedList<>();
        queue.offer(new Position(0,0));
        visited[0][0] = true;

        while(!queue.isEmpty()) {
            Position p = queue.poll();

            for(int i=0; i<4; i++) {
                int x = p.getX()+dx[i];
                int y = p.getY()+dy[i];
                if(x < 0 || x >= maze.length || y < 0 || y >= maze[0].length) {
                    continue;
                }
                if(maze[x][y] != 0 && visited[x][y] == false) {
                    queue.offer(new Position(x, y));
                    visited[x][y] = true;
                    if(maze[x][y] == 1 || maze[x][y] > maze[p.getX()][p.getY()] + 1) {
                        maze[x][y] = maze[p.getX()][p.getY()] + 1;
                    }
                }
            }
        }
        System.out.print(maze[maze.length-1][maze[0].length-1]);
    }

    public static class Position {
        private int x;
        private int y;

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

        public int getX() {
            return this.x;
        }

        public int getY() {
            return this.y;
        }
    }
}

0개의 댓글