본문 바로가기
알고리즘/BFS

[백준 2178] 미로 탐색/ 자바 / bfs

by 순원이 2024. 7. 21.

#문제         

레벨: S1
알고리즘: bfs

풀이시간: 30분
힌트 참조 유무:

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

 


#문제 풀이        

bfs 문제의 기본 문제이다. queue와 visited[][]배열을 이용해서 길을 되돌아 가지도 않고 최단 거리를 찾을 수 있다. visited[][]배열을 쓰고 싶지 않다면 distance[][]배열에 해당위치에 도달하기 까지 걸린 이동횟수를 기입하면 된다. distance[][]에 0 이 아닌 숫자가 있다면 방문한 것이므로 해당 위치는 또 queue에 넣지않는다.(방문하지 않는다.)

 


#풀이 코드      

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

public class Main {
    static int N, M;
    static char[][] maze;
    static boolean[][] visited;
    static int[] dx = {-1, 1, 0, 0};
    static int[] dy = {0, 0, -1, 1};

    static class Position {
        int x, y, distance;

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

    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 char[N][M];
        visited = new boolean[N][M];

        for (int i = 0; i < N; i++) {
            String line = br.readLine();
            for (int j = 0; j < M; j++) {
                maze[i][j] = line.charAt(j);
            }
        }

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

    public static int bfs() {
        Queue<Position> queue = new LinkedList<>();
        queue.offer(new Position(0, 0, 1));
        visited[0][0] = true;

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

            if (current.x == N - 1 && current.y == M - 1) {
                return current.distance;
            }

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

                if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
                    if (maze[nx][ny] == '1' && !visited[nx][ny]) {
                        queue.offer(new Position(nx, ny, current.distance + 1));
                        visited[nx][ny] = true;
                    }
                }
            }
        }

        return -1; // 도달할 수 없는 경우
    }
}