Problemas de la corriente del Atlántico Pacífico (JAVA)

Dada una matriz mxn de números enteros no negativos que representan la altura de cada celda en un continente. El "Pacífico" está en los límites izquierdo y superior del continente, mientras que el "Atlántico" está en los límites derecho e inferior del continente.

Se estipula que el flujo de agua solo puede fluir en las cuatro direcciones: arriba, abajo, izquierda y derecha, y solo puede fluir de arriba a abajo o a la misma altura.

Encuentre las coordenadas de aquellas unidades terrestres donde el agua fluye tanto hacia el Océano Pacífico como hacia el Océano Atlántico.

pista:

1. El orden de las coordenadas de salida no es importante
2. Tanto m como n son menores que 150

Ejemplo:

Dada la siguiente matriz de 5x5:

Océano Pacífico ~ ~ ~ ~ ~
1 2 2 3 (5) *
3 2 3 (4) (4) *
2 4 (5) 3 1 *
(6) (7) 1 4 5 *
(5) 1 1 2 4 *
          • océano Atlántico

devolver:

[[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (con corchetes en la figura anterior unidad).

analizar:

Esta cuestión es encontrar una coordenada que pueda llegar tanto al Océano Pacífico como al Océano Atlántico, sin embargo, este proceso generalmente no se puede completar en una búsqueda en profundidad, por lo que partimos de cada límite y buscamos contra corriente. Luego use dos matrices bidimensionales para registrar, lo que equivale a 44 búsquedas profundas. Para obtener respuestas específicas, consulte el siguiente código.

class Solution {
    
    
    public List<List<Integer>> pacificAtlantic(int[][] heights) {
    
    
        int m = heights.length;
        int n = heights[0].length;
        int[][] ao = new int[m][n];//太平洋的节点记录矩阵
        int[][] pa = new int[m][n];//大西洋的节点记录矩阵
        //1. 从上下边界开始两大洋的回流搜索,变动的是列
        for(int i=0;i<n;i++){
    
    
            dfs(heights,pa,0,i);
            dfs(heights,ao,m-1,i);
        }
        //2. 从左右边界开始两大洋的回流搜索,变动的是行
        for(int i=0;i<m;i++){
    
    
            dfs(heights,pa,i,0);
            dfs(heights,ao,i,n-1);
        }
        //3. 输出交叠的坐标
        List<List<Integer>> cnt = new ArrayList<List<Integer>>();
        for(int i=0;i<m;i++){
    
    
            for(int j=0;j<n;j++){
    
    
                if(ao[i][j]==1&&pa[i][j]==1){
    
    
                    cnt.add(Arrays.asList(i,j));
                }
            }
        }
        return cnt;
    }

    public static void dfs(int[][] heights,int[][] tmp,int cur_i,int cur_j){
    
    
        //标记可以从海洋流回经过的节点
        tmp[cur_i][cur_j]=1;
        //开始深度优先搜索当前坐标的4个方向
        //1. 设置更新的坐标
        int[] di=new int[]{
    
    1,-1,0,0};//上下移动
        int[] dj=new int[]{
    
    0,0,1,-1};//左右移动
        int new_i=0;
        int new_j=0;
        //2. 更新坐标并递归搜索
        for(int index=0;index<4;index++){
    
    
            new_i=cur_i+di[index];
            new_j=cur_j+dj[index];
            //判断下标是否越界
            if(new_i<0||new_j<0||new_i>=heights.length||new_j>=heights[0].length){
    
    
                continue;
            }
            if(heights[cur_i][cur_j]<=heights[new_i][new_j]&&tmp[new_i][new_j]!=1){
    
    
                dfs(heights,tmp,new_i,new_j);
            }
        }
    }
}
class Solution {
    
    
    public List<int[]> pacificAtlantic(int[][] matrix) {
    
    
        List<int[]> ret = new List<>();
        int m = matrix.length;
        if(m < 1) return ret;
        int n = matrix[0].length;
        boolean[][] Pacific = new boolean[m][n];
        boolean[][] Atlantic = new boolean[m][n];
        for(int i = 0; i < m; ++i){
    
    
            dfs(matrix, i, 0, Pacific, matrix[i][0]);
            dfs(matrix, i, n-1, Atlantic, matrix[i][n-1]);
        }
        for(int i = 0; i < n; ++i){
    
    
            dfs(matrix, 0, i, Pacific, matrix[0][i]);
            dfs(matrix, m-1, i, Atlantic, matrix[m-1][i]);    
        }
        for(int i = 0; i < m; ++i){
    
    
            for(int j = 0; j < n; ++j){
    
    
                if(Pacific[i][j] && Atlantic[i][j])
                    ret.add(new int[]{
    
    i,j});
            }
        }
        return ret;
    }

    private void dfs(int[][] m, int x, int y, boolean[][] visited, int pre){
    
    
        if(x<0 || y<0 || x>=m.length || y >=m[0].length || visited[x][y] || m[x][y]< pre) return;
        visited[x][y] = true;
        dfs(m,x+1,y,visited,m[x][y]);
        dfs(m,x-1,y,visited,m[x][y]);
        dfs(m,x,y+1,visited,m[x][y]);
        dfs(m,x,y-1,visited,m[x][y]);
        
    }
}

Supongo que te gusta

Origin blog.csdn.net/smile66688/article/details/120377590
Recomendado
Clasificación