[BOJ] 2178. 미로 탐색

2021. 3. 16. 15:37알고리즘/백준 문제 풀이

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

접근 방법

미로 탐색이다.

BFS의 전형적인 문제로 내가 방문한 point를 늘려가면서 진행을 하면 문제를 쉽게 풀 수 있다.

Need Know

  1. BFS

전체 코드 ( Java )

import java.io.*;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;

class Main{
    static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    static BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
    static int N, M;
    static int[][] map;
    static int[] aa = {-1,1,0,0};
    static int[] bb = {0,0,1,-1};
    static Point start;
    static Point end;
    static Queue<Point> queue;
    public static void main(String[] args) throws IOException{
        set();
        solve();

        br.close();
        bw.flush();
        bw.close();
    }
    static void set() throws IOException {
        StringTokenizer st = new StringTokenizer(br.readLine());
        N = Integer.parseInt(st.nextToken());
        M = Integer.parseInt(st.nextToken());
        map = new int[N+1][M+1];

        for(int i=0; i<N; i++){
            String str = br.readLine();
            for(int k=0; k<M; k++){
                if(str.charAt(k) == '1'){
                    map[i][k] = 1;
                }
            }
        }
        start = new Point(0,0);
        end = new Point(N,M);
        queue = new LinkedList<>();
        queue.add(start);
    }
    static void solve() throws IOException {
        bfs();

        bw.write(map[N-1][M-1]+"");
    }
    static void bfs(){
        while(!queue.isEmpty()){
            Point now = queue.poll();
            if(now.a == end.a && now.b == end.b){
                break;
            }
            for(int i=0; i<4; i++){
                int na = aa[i] + now.a;
                int nb = bb[i] + now.b;

                if(na < 0 || nb < 0 || na >= N || nb >= M) continue;

                if(map[na][nb] == 1){
                    queue.add(new Point(na,nb));
                    map[na][nb] = map[now.a][now.b] + 1;
                }
            }
        }
    }
    static class Point{
        int a,b;

        public Point(int a, int b) {
            this.a = a;
            this.b = b;
        }
    }
}

'알고리즘 > 백준 문제 풀이' 카테고리의 다른 글

[BOJ] 1182. 부분수열의 합  (0) 2021.04.21
[BOJ] 2573. 빙산  (0) 2021.03.26
[BOJ] 2606. 바이러스  (0) 2021.03.16
[BOJ] 1339. 단어 수학  (0) 2021.03.15
[BOJ] 1436. 영화감독 숌  (0) 2021.03.05