# Java BFS solution, 26ms

• The idea is searching the units with greater height starting from the four edges. Not yet optimized:

``````public class Solution {
public List<int[]> pacificAtlantic(int[][] matrix) {
List<int[]> res=new ArrayList<>();
if (matrix.length==0) return res;
int m=matrix.length, n=matrix[0].length;
int[][] pacific=new int[m][n];
int[][] atlantic=new int[m][n];
boolean[][] visited=new boolean[m][n];
//check the pacific part
int[] dx={0,0,1,-1}, dy={1,-1,0,0};
while (!q.isEmpty()){
int[] pos=q.poll();
pacific[pos[0]][pos[1]]=1;
for (int k=0;k<4;k++){
int x=pos[0]+dx[k], y=pos[1]+dy[k];
if (x<0 || y<0 || x==m || y==n || visited[x][y]==true || matrix[x][y]<matrix[pos[0]][pos[1]] || pacific[x][y]==1) continue;
visited[x][y]=true;
}
}
//check the atlantic part
visited=new boolean[m][n];
while (!q.isEmpty()){
int[] pos=q.poll();
atlantic[pos[0]][pos[1]]=1;
for (int k=0;k<4;k++){
int x=pos[0]+dx[k], y=pos[1]+dy[k];
if (x<0 || y<0 || x==m || y==n || visited[x][y]==true || matrix[x][y]<matrix[pos[0]][pos[1]] || atlantic[x][y]==1) continue;
visited[x][y]=true;
}
}
for (int i=0;i<m;i++){
for (int j=0;j<n;j++){
if (pacific[i][j]==1 && atlantic[i][j]==1) res.add(new int[]{i,j});
}
}
return res;
}
}
``````

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.