https://programmers.co.kr/learn/courses/30/lessons/1844

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๊ฒŒ์ž„ ๋งต ์ตœ๋‹จ๊ฑฐ๋ฆฌ

[[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,1],[0,0,0,0,1]] 11 [[1,0,1,1,1],[1,0,1,0,1],[1,0,1,1,1],[1,1,1,0,0],[0,0,0,0,1]] -1

programmers.co.kr

 

 

 

 

 

๊ทธ๋ž˜ํ”„ ํƒ์ƒ‰ ๋ฌธ์ œ์ด๋‹ค. ์˜ˆ์ „์— ํ’€์—ˆ๋˜ ๋ฐฑ์ค€ ํ† ๋งˆํ†  ๋ฌธ์ œ(https://www.acmicpc.net/problem/7576)์™€ ๋น„์Šทํ•˜๋‹ค๊ณ  ์ƒ๊ฐํ•ด์„œ Queue๋ฅผ ์‚ฌ์šฉํ•œ BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ํ’€์—ˆ๋‹ค.

 

Player ํด๋ž˜์Šค๋ฅผ ๋งŒ๋“ค์–ด ์ขŒํ‘œ ๊ฐ’๊ณผ ์ด๋™ํ•œ ์นธ ์ˆ˜๋ฅผ ์ €์žฅํ•˜๋„๋ก ํ–ˆ๋‹ค.

 

 

 

 

์ฝ”๋“œ

import java.util.*;

class Solution {
    static int[] dx = {1, -1, 0, 0};
    static int[] dy = {0, 0, 1, -1};
    static boolean[][] visited;
    
    static class Player {
        int x;
        int y;
        int count;
        
        public Player(int x, int y, int count) {
            this.x = x;
            this.y = y;
            this.count = count;
        }
    }
    
    public int solution(int[][] maps) {
        visited = new boolean[maps.length][maps[0].length];
        
        int answer = bfs(maps, 0, 0);
        
        return answer;
    }
    
    public int bfs(int[][] maps, int a, int b) {
        Queue<Player> queue = new LinkedList<Player>();
        
        queue.add(new Player(a, b, 1));
        
        while(!queue.isEmpty()) {
            Player player = queue.poll();
            visited[player.x][player.y] = true;
            
            if(player.x == maps.length - 1 && player.y == maps[0].length - 1) {
                return player.count;
            }
            
            for(int i = 0; i < 4; i++) {
                int nx = player.x + dx[i];
                int ny = player.y + dy[i];
                int count = player.count;
                
                if(0 <= nx && nx < maps.length && 0 <= ny && ny < maps[0].length) {
                    if(maps[nx][ny] == 1 && !visited[nx][ny]) {
                        queue.add(new Player(nx, ny, count + 1));
                        visited[nx][ny] = true;
                    }
                }
            }
        }
        
        return -1;
    }
}

 

 

 

 

 

๊ฒฐ๊ณผ

์ •ํ™•์„ฑ๊ณผ ํšจ์œจ์„ฑ ๋ชจ๋‘ ํ†ต๊ณผํ–ˆ๋‹ค!

giraffe_