1. ๋ฌธ์ œ :https://school.programmers.co.kr/learn/courses/30/lessons/1844

 

2. ํ’€์ด

์ตœ๋‹จ๊ฑฐ๋ฆฌ์˜ ๊ฒฝ์šฐ bfs๋กœ!

 

3. ์ฝ”๋“œ

import java.util.*;

class Solution {
    
    // ์ƒํ•˜์ขŒ์šฐ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋Š” ์ขŒํ‘œ
    int[] dx = {0, 1, -1, 0};
    int[] dy = {1, 0, 0, -1};
    
    public int solution(int[][] maps) {
        
        int answer = 0;

        int[][] visited = new int[maps.length][maps[0].length];

        bfs(maps, visited);
        answer = visited[maps.length - 1][maps[0].length - 1]; // ์ƒ๋Œ€ ํŒ€ ์ง„์˜ ์ขŒํ‘œ

        if (answer == 0) { // ์ƒ๋Œ€ ํŒ€ ์ง„์˜์— ๋„๋‹ฌํ•˜์ง€ ๋ชปํ•œ ๊ฒฝ์šฐ
            answer = -1;
        }

        return answer;
    }
    
    public void bfs(int[][] maps, int[][] visited) {

        Queue<int[]> q = new LinkedList<>();
        q.add(new int[]{0, 0}); // Queue์— ์‹œ์ž‘ ์ •์  ์ถ”๊ฐ€
        visited[0][0] = 1;

        while (!q.isEmpty()) { // ๋” ๋‚˜์•„๊ฐˆ ์ •์ ์ด ์—†์„ ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณต

            int[] current = q.poll(); // ์ •์  ํ•˜๋‚˜ ๊บผ๋‚ด๊ธฐ
            int X = current[0];
            int Y = current[1];

            for (int i = 0; i < 4; i++) {

                int nX = X + dx[i];
                int nY = Y + dy[i];

                // ์ขŒํ‘œ๊ฐ€ maps์—์„œ ๋ฒ—์–ด๋‚  ๊ฒฝ์šฐ ๋‹ค์Œ ๋ฐ˜๋ณต์œผ๋กœ ๋„˜์–ด๊ฐ„๋‹ค
                if (nX < 0 || nX > maps.length - 1 || nY < 0 || nY > maps[0].length - 1) {
                    continue;
                }

                // ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์•˜๊ณ , ๋ฒฝ์ด ์•„๋‹ ๊ฒฝ์šฐ
                if (visited[nX][nY] == 0 && maps[nX][nY] == 1) {
                    visited[nX][nY] = visited[X][Y] + 1;
                    q.add(new int[]{nX, nY});
                }
            }
        }
    }
}
  • ๋„ค์ด๋ฒ„ ๋ธ”๋Ÿฌ๊ทธ ๊ณต์œ ํ•˜๊ธฐ
  • ๋„ค์ด๋ฒ„ ๋ฐด๋“œ์— ๊ณต์œ ํ•˜๊ธฐ
  • ํŽ˜์ด์Šค๋ถ ๊ณต์œ ํ•˜๊ธฐ
  • ์นด์นด์˜ค์Šคํ† ๋ฆฌ ๊ณต์œ ํ•˜๊ธฐ