代码:

class Solution {
    static int[][] dirs = {{-1,0},{1,0},{0,-1},{0,1}};
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
        List<List<Integer>> res = new ArrayList<>();
        int[][] ocean1 = new int[heights.length][heights[0].length];
        int[][] ocean2 = new int[heights.length][heights[0].length];
        Queue<int[]> queue1 = new LinkedList<>();
        Queue<int[]> queue2 = new LinkedList<>();
        for(int i=0;i<heights.length;i++){
            int[] cur1 = {i,0};
            int[] cur2 = {i,heights[0].length-1};
            ocean1[i][0] = 1;
            ocean2[i][heights[0].length-1] = 1;
            queue1.add(cur1);
            queue2.add(cur2);
        }
        for(int j=0;j<heights[0].length;j++){
            int[] cur1 = {0,j};
            int[] cur2 = {heights.length-1,j};
            ocean1[0][j] = 1;
            ocean2[heights.length-1][j] = 1;
            queue1.add(cur1);
            queue2.add(cur2);
        }
        while(queue1.size()!=0){
            int[] cur = queue1.poll();
            for(int i=0;i<dirs.length;i++){
                int x = cur[0] + dirs[i][0];
                int y = cur[1] + dirs[i][1];
                if(x<0||y<0||x==heights.length||y==heights[0].length)continue;
                if(ocean1[x][y]==1)continue;
                if(heights[x][y]>=heights[cur[0]][cur[1]]){
                    ocean1[x][y] = 1;
                    int[] cell = {x,y};
                    queue1.add(cell);
                }
            }
        }
        while(queue2.size()!=0){
            int[] cur = queue2.poll();
            for(int i=0;i<dirs.length;i++){
                int x = cur[0] + dirs[i][0];
                int y = cur[1] + dirs[i][1];
                if(x<0||y<0||x==heights.length||y==heights[0].length)continue;
                if(ocean2[x][y]==1)continue;
                if(heights[x][y]>=heights[cur[0]][cur[1]]){
                    ocean2[x][y] = 1;
                    int[] cell = {x,y};
                    queue2.add(cell);
                }
            }
        }
        for(int i=0;i<heights.length;i++){
            for(int j=0;j<heights[0].length;j++){
                if(ocean1[i][j]==1&&ocean2[i][j]==1){
                    List<Integer> cell = Arrays.asList(i,j);
                    res.add(cell);
                }
            }
        }
        return res;
    }
}

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐