Skip to content

Commit c93bf82

Browse files
week9 mission - Pacific Atlantic Water Flow
1 parent b2c1388 commit c93bf82

File tree

1 file changed

+60
-0
lines changed

1 file changed

+60
-0
lines changed
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
- ๋ฌธ์ œ: https://leetcode.com/problems/pacific-atlantic-water-flow/
2+
- ํ’€์ด: https://algorithm.jonghoonpark.com/2024/03/03/leetcode-417
3+
4+
```java
5+
public class Solution {
6+
public List<List<Integer>> pacificAtlantic(int[][] heights) {
7+
List<List<Integer>> result = new ArrayList<>();
8+
9+
for (int i = 0; i < heights.length; i++) {
10+
for (int j = 0; j < heights[0].length; j++) {
11+
System.out.printf("\n\ninit Flow : %d, %d\n", i, j);
12+
Flow flow = new Flow();
13+
dfs(flow, heights, Integer.MAX_VALUE, i, j);
14+
if (flow.flowToAtlanticOcean && flow.flowToPacificOcean) {
15+
result.add(List.of(i, j));
16+
}
17+
}
18+
}
19+
20+
return result;
21+
}
22+
23+
private void dfs(Flow flow, int[][] heights, int prev, int i, int j) {
24+
if (i == -1 || j == -1) {
25+
flow.flowToPacificOcean = true;
26+
return;
27+
}
28+
29+
if (i == heights.length || j == heights[0].length) {
30+
flow.flowToAtlanticOcean = true;
31+
return;
32+
}
33+
34+
if (heights[i][j] == -1 || heights[i][j] > prev || flow.flowToAtlanticOcean && flow.flowToPacificOcean) {
35+
return;
36+
}
37+
38+
int currentHeight = heights[i][j];
39+
heights[i][j] = -1;
40+
41+
dfs(flow, heights, currentHeight, i + 1, j);
42+
dfs(flow, heights, currentHeight, i - 1, j);
43+
dfs(flow, heights, currentHeight, i, j + 1);
44+
dfs(flow, heights, currentHeight, i, j - 1);
45+
46+
heights[i][j] = currentHeight;
47+
}
48+
}
49+
50+
class Flow {
51+
boolean flowToPacificOcean;
52+
boolean flowToAtlanticOcean;
53+
}
54+
```
55+
56+
## TC, SC
57+
58+
heights์˜ ๊ธธ์ด๋ฅผ `w`, heights[0]์˜ ๊ธธ์ด๋ฅผ `h`๋กœ ์ •์˜ํ–ˆ์„ ๋•Œ,
59+
์ด ์ฝ”๋“œ์˜ ์‹œ๊ฐ„ ๋ณต์žก๋„๋Š” `O((w \* h)^2)`, ๊ณต๊ฐ„ ๋ณต์žก๋„๋Š” `O(w \* h)` ์ด๋‹ค.
60+
์‹œ๊ฐ„ ๋ณต์žก๋„๊ฐ€ ์ €๋ ‡๊ฒŒ ๋‚˜์˜จ ์ด์œ ๋Š” ๋ชจ๋“  ์ขŒํ‘œ์— ๋Œ€ํ•ด์„œ dfs๋ฅผ ์ง„ํ–‰ํ•˜๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

0 commit comments

Comments
ย (0)