[Neetcode] Islands and Treasure

whitehousechef·2025년 8월 11일

https://neetcode.io/problems/islands-and-treasure?list=neetcode150

initial

typical bfs q

also we cant do

0<=next_row<m for java

It should be 
0<=next_row && next_row<m

sol

class Solution {
    public void islandsAndTreasure(int[][] graph) {
        Queue<int[]> queue = new LinkedList<>();
        int m=graph.length;
        int n=graph[0].length;
        for(int i =0;i<m;i++){
            for(int j=0; j<n;j++){
                if(graph[i][j]==0){
                    queue.offer(new int[]{i,j,0});
                }
            }
        }
        int[][] directions = {{1,0},{-1,0},{0,1},{0,-1}};
        while(!queue.isEmpty()){
            int[] info = queue.poll();
            int row=info[0],col=info[1],dist=info[2];
            for(int[] dir:directions){
                int next_row = dir[0]+row, next_col=dir[1]+col;
                if(0<=next_row && next_row<m && 0<=next_col && next_col<n
                 && graph[next_row][next_col]==2147483647){
                    queue.offer(new int[]{next_row,next_col,dist+1});
                    graph[next_row][next_col]=dist+1;
                }
            }
        }
    }
}

complexity

m*n time and space

0개의 댓글