Algorithm/baekjoon

미로 탐색

마닐라 2022. 2. 19. 12:59

📍 문제 설명

💡 접근

전형적인 BFS 문제

 

👩‍💻 코드

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;

public class Main {
    static int n, m, v, e, k, answer, cnt;
    static int[][] board;
    static int[] arr;
    static long[] dp;
    static boolean[][] visited;
    static int[] dx = {-1,1,0,0};
    static int[] dy = {0,0,-1,1};
    static ArrayList<Integer> list = new ArrayList<>();
    static StringBuilder sb = new StringBuilder();

    public static void main(String[] args) {
        Scanner kb = new Scanner(System.in);
        Main T = new Main();
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        n = kb.nextInt();
        m = kb.nextInt();
        kb.nextLine();
        board = new int[n+1][m+1];
        visited = new boolean[n+1][m+1];
        for(int i = 1; i <= n; i++) {
            String[] s = kb.nextLine().split("");
            for(int j = 0; j < m; j++) {
                board[i][j+1] = Integer.parseInt(s[j]);
            }
        }

        T.solution();
        System.out.println(board[n][m]);
    }


    private void solution() {
        Queue<Point> q = new LinkedList<>();
        q.offer(new Point(1, 1));
        visited[1][1] = true;

        while(!q.isEmpty()) {
            Point cp = q.poll();
            for(int i = 0; i < 4; i++) {
                int nx = cp.x + dx[i];
                int ny = cp.y + dy[i];
                if(nx<=0 || ny<=0 || nx>n || ny>m) continue;

                if(board[nx][ny] == 1 && !visited[nx][ny]) {
                    visited[nx][ny] = true;
                    board[nx][ny] = board[cp.x][cp.y] + 1;
                    q.offer(new Point(nx, ny));
                }
            }

        }
    }

    private class Point {
        private int x;
        private int y;

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

'Algorithm > baekjoon' 카테고리의 다른 글

나이트의 이동  (0) 2022.02.19
토마토  (0) 2022.02.19
단지번호 붙이기  (0) 2022.02.18
이분 그래프  (0) 2022.02.18
연결 요소의 개수  (0) 2022.02.18