본문 바로가기
Algorithm (PS)/백준

[백준] 2178. 미로탐색 (Java) [BFS 최단거리)

by 태크민 2023. 7. 11.

문제

https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

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

www.acmicpc.net

 

 

알고리즘

BFS 최단거리

 

 

풀이

BFS를 통해 4방향 탐색을 하며 최단거리를 구하는 문제다.

단 벽이 있는 경우, 이미 방문한 좌표, 맵 밖을 벗어나는 경우를 주의하며 이동을 해야한다.

 

 

코드

package com.company;

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 Test_BFS_Min_Distance {
    static int N, M;
    static int[][] map;

    static int[][] moveDir = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    static int[][] cnt;

    public static void main(String[] args) throws IOException {
        BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st = new StringTokenizer(bf.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());

        map = new int[N][M];
        cnt = new int[N][M];
        for (int i = 0; i < N; i++) {
            String s = bf.readLine();
            for (int j = 0; j < M; j++) {
                map[i][j] = s.charAt(j) - '0';
            }
        }

        BFS();
    }

    public static boolean isInside(int x, int y){
        return x>=0 && x<N && y>=0 && y<M;
    }

    //최단 거리 탐색
    static void BFS() {
        Queue<Point> q = new LinkedList<>();
        q.add(new Point(0, 0));
        cnt[0][0] = 1;
        while (!q.isEmpty()) {
            Point p = q.poll();
            int cX = p.x;
            int cY = p.y;
            if (cX == N - 1 && cY == M - 1) {
                System.out.println(cnt[cX][cY]);
                return;
            }
            for (int i = 0; i < 4; i++) {
                int nx = cX + moveDir[i][0];
                int ny = cY + moveDir[i][1];
                if(!isInside(nx,ny)) continue; //맵 밖을 벗어나는 경우
                if (cnt[nx][ny] > 0) continue; //방문한 좌표라면
                if(map[nx][ny]==0) continue; //벽이라면
                cnt[nx][ny] = cnt[cX][cY] + 1;
                q.add(new Point(nx, ny));
            }
        }
    }

    static public class Point {
        int x, y;

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