前言:正好碰见Leetcode有一次在线笔试,测试一下,还是挺开心的,全做出来了Rank:98/869。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
博客链接:mcf171的博客
——————————————————————————————
Given an m x n
matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges.
Water can only flow in four directions (up, down, left, or right) from a cell to another one with height equal or lower.
Find the list of grid coordinates where water can flow to both the Pacific and Atlantic ocean.
Note:
- The order of returned grid coordinates does not matter.
- Both m and n are less than 150.
Example:
Given the following 5x5 matrix: Pacific ~ ~ ~ ~ ~ ~ 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 * * * * * * Atlantic Return: [[0, 4], [1, 3], [1, 4], [2, 2], [3, 0], [3, 1], [4, 0]] (positions with parentheses in above matrix).这个题目思路很明确,用两个数组来记录哪些点可以去大西洋,哪些可以去太平洋,然后将又能去大西洋,又能去太平洋的点输出。判断哪些点能去的思路用启发式的方式递归做。 Your runtime beats 93.59% of java submissions
public class Solution {
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> results = new ArrayList<int[]>();
int m = matrix.length;
if(m == 0) return results;
int n = matrix[0].length;
int[][] toAtlantic = new int[m][n];
int[][] toPacific = new int[m][n];
for(int i = 0; i< m; i ++){
toAtlantic[i][n-1] = 1;
toPacific[i][0] = 1;
reactiveCell(matrix,toAtlantic,i,n-1,m,n);
reactiveCell(matrix,toPacific,i,0,m,n);
}
for(int i = 0; i < n; i ++){
toAtlantic[m-1][i] = 1;
toPacific[0][i] = 1;
reactiveCell(matrix,toAtlantic,m-1,i,m,n);
reactiveCell(matrix,toPacific,0,i,m,n);
}
for(int i = 0; i < m; i ++)
for(int j = 0 ; j < n ; j ++){
if(toAtlantic[i][j] == 1 && toPacific[i][j] == 1){ int[]result = new int[]{i,j}; results.add(result);}
}
return results;
}
public void reactiveCell(int[][] matrix,int[][] markMatrix,int i,int j,int m,int n){
if( i > 0 && matrix[i-1][j] >= matrix[i][j] && markMatrix[i-1][j] == 0) {markMatrix[i-1][j] = 1;reactiveCell(matrix,markMatrix,i-1,j,m,n);}
if( i < m-1 && matrix[i+1][j] >= matrix[i][j] && markMatrix[i+1][j] == 0) {markMatrix[i+1][j] = 1;reactiveCell(matrix,markMatrix,i+1,j,m,n);}
if( j > 0 && matrix[i][j-1] >= matrix[i][j] && markMatrix[i][j-1] == 0) {markMatrix[i][j-1] = 1; reactiveCell(matrix,markMatrix,i,j-1,m,n);}
if( j < n-1 && matrix[i][j+1] >= matrix[i][j] && markMatrix[i][j+1] == 0) {markMatrix[i][j+1] = 1;reactiveCell(matrix,markMatrix,i,j+1,m,n);}
}
}