Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commite98164c

Browse files
committed
add 417 pacific atlantic ware flow
1 parentcbfb739 commite98164c

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
classSolution {
2+
publicList<List<Integer>>pacificAtlantic(int[][]matrix) {
3+
List<List<Integer>>result =newArrayList<>();
4+
introw =matrix.length;
5+
if (row ==0)
6+
returnresult;
7+
intcol =matrix[0].length;
8+
boolean [][]pacific =newboolean [row][col];
9+
boolean [][]atlantic =newboolean [row][col];
10+
// go through every single position in the first row
11+
for (inti=0;i<col;i++) {
12+
//run dfs on first row
13+
dfs(matrix,0,i,matrix[0][i],pacific);
14+
//run dfs on last row
15+
dfs(matrix,row-1,i,matrix[row-1][i],atlantic);
16+
}
17+
// get the position in most left column
18+
for (inti=0;i<row;i++) {
19+
dfs(matrix,i,0,matrix[i][0],pacific);
20+
dfs(matrix,i,col-1,matrix[i][col-1],atlantic);
21+
}
22+
for (inti=0;i<row;i++) {
23+
for (intj=0;j<col;j++) {
24+
// if the position is visited in both the Pacific and Atlantic oceans, we add to the result
25+
if (pacific[i][j] &&atlantic[i][j]) {
26+
List<Integer>currentResult =newArrayList<>();
27+
currentResult.add(i);
28+
currentResult.add(j);
29+
result.add(currentResult);
30+
}
31+
}
32+
}
33+
returnresult;
34+
}
35+
36+
publicvoiddfs(int [][]matrix,intr,intc,intpreHeight,boolean [][]visited) {
37+
if (r <0 ||c <0 ||r >=matrix.length ||c >=matrix[0].length ||preHeight >matrix[r][c] ||visited[r][c])
38+
return;
39+
visited[r][c] =true;
40+
dfs(matrix,r+1,c,matrix[r][c],visited);
41+
dfs(matrix,r-1,c,matrix[r][c],visited);
42+
dfs(matrix,r,c+1,matrix[r][c],visited);
43+
dfs(matrix,r,c-1,matrix[r][c],visited);
44+
}
45+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp