๐Ÿ’ปTech/โ˜•Java

[Java] ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

_viper_ 2023. 9. 28. 16:20
๋ฐ˜์‘ํ˜•

๐Ÿ“„ ๋ฌธ์ œ

๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

 

๐Ÿ’ก ํ’€์ด

BFS(๋„ˆ๋น„ ์šฐ์„  ํƒ์ƒ‰) ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•˜์—ฌ ๋งต์„ ํ†ต๊ณผ ๊ฐ€๋Šฅํ•œ ๋ฐฉ์•ˆ๋“ค์„ ํƒ์ƒ‰ํ•˜๊ณ , ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ์ฐพ์•„ answer ๋ณ€์ˆ˜์— ์ €์žฅํ•œ ํ›„ ๋ฐ˜ํ™˜ํ•ฉ๋‹ˆ๋‹ค.

 

import java.util.*;

class Solution {
    public int solution(int[][] maps) {
        int answer = 0;
        int n = maps.length;
        int m = maps[0].length;
        
        // ์ด๋™ ๊ฐ€๋Šฅํ•œ ๋ฐฉํ–ฅ (์ƒ,ํ•˜,์šฐ,์ขŒ)
        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        
        Queue<int[]> queue = new LinkedList<>();
        queue.offer(new int[]{0, 0, 1}); // ์‹œ์ž‘ ์œ„์น˜ (0, 0)์—์„œ ์ถœ๋ฐœํ•˜๋ฏ€๋กœ ํ์— ์ถ”๊ฐ€

        while (!queue.isEmpty()) {
            int[] currentPosition = queue.poll();
            int x = currentPosition[0];
            int y = currentPosition[1];
            int distance = currentPosition[2];

       	    // ๋ชฉ์ ์ง€์— ๋„๋‹ฌํ•˜๋ฉด ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๋ฐ˜ํ™˜ํ›„ ์ข…๋ฃŒ
            // ๋„์ฐฉ ๊ฐ€๋Šฅํ•œ ์—ฌ๋Ÿฌ ๋ฐฉ์•ˆ์ด ์žˆ๋”๋ผ๋„, ์ตœ๋‹จ ๊ฑฐ๋ฆฌ ๋ฐฉ์•ˆ์ด ์ œ์ผ ๋จผ์ € ๋„์ฐฉ
            if (x == n - 1 && y == m - 1) { 
                answer = distance;
                break;
            }

            for (int[] dir : directions) {
                int newX = x + dir[0];
                int newY = y + dir[1];

                // ์ด๋™ ๊ฐ€๋Šฅํ•œ ์œ„์น˜์ด๋ฉด ํ์— ์ถ”๊ฐ€ํ•˜๊ณ  ํ•ด๋‹น ์œ„์น˜๋ฅผ ๋ฒฝ์œผ๋กœ ํ‘œ์‹œ (๋ฐฉ๋ฌธ ์ฒ˜๋ฆฌ)
                if (newX >= 0 && newX < n && 
                    newY >= 0 && newY < m && 
                    maps[newX][newY] == 1) {
                    queue.offer(new int[]{newX, newY, distance + 1});
                    maps[newX][newY] = 0;
                }
            }
        }
        
        if (answer == 0) {
            // ๋ชฉ์ ์ง€์— ๋„๋‹ฌํ•  ์ˆ˜ ์—†๋Š” ๊ฒฝ์šฐ -1 ๋ฐ˜ํ™˜
            return -1;
        }
        
        return answer;
    }
}