Skip to content

Commit c92ff77

Browse files
update post
1 parent c17727c commit c92ff77

File tree

1 file changed

+74
-1
lines changed

1 file changed

+74
-1
lines changed

_posts/2024-03-03-leetcode-417.md

Lines changed: 74 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,20 @@
22
layout: post
33
title: (Leetcode) 417 - Pacific Atlantic Water Flow
44
categories: [스터디-알고리즘]
5-
tags: [파이썬, 알고리즘, python, algorithm, Leetcode, graph, dfs, matrix, visit]
5+
tags:
6+
[
7+
파이썬,
8+
알고리즘,
9+
python,
10+
algorithm,
11+
Leetcode,
12+
graph,
13+
dfs,
14+
matrix,
15+
visit,
16+
java,
17+
자바,
18+
]
619
date: 2024-03-03 12:00:00 +0900
720
---
821

@@ -137,3 +150,63 @@ dfs(r, c - 1, visit, heights[r][c])
137150
참고로 주어진 예시에서 (1,4) 같은 경우에는 직선적인 케이스만 고려해서는 찾을 수 없는 값이다.
138151
(1,4) 가 pacific에 들어가려면 (1,4) -> (1,3) -> (0,3) 순으로 거쳐야 한다. (왼쪽으로 갔다가 위로 올라간다)
139152
따라서 dfs를 따라 모든 경로를 탐색해야 한다.
153+
154+
## 자바로 다시 풀기 (24.06.30)
155+
156+
```java
157+
public class Solution {
158+
public List<List<Integer>> pacificAtlantic(int[][] heights) {
159+
List<List<Integer>> result = new ArrayList<>();
160+
161+
for (int i = 0; i < heights.length; i++) {
162+
for (int j = 0; j < heights[0].length; j++) {
163+
System.out.printf("\n\ninit Flow : %d, %d\n", i, j);
164+
Flow flow = new Flow();
165+
dfs(flow, heights, Integer.MAX_VALUE, i, j);
166+
if (flow.flowToAtlanticOcean && flow.flowToPacificOcean) {
167+
result.add(List.of(i, j));
168+
}
169+
}
170+
}
171+
172+
return result;
173+
}
174+
175+
private void dfs(Flow flow, int[][] heights, int prev, int i, int j) {
176+
if (i == -1 || j == -1) {
177+
flow.flowToPacificOcean = true;
178+
return;
179+
}
180+
181+
if (i == heights.length || j == heights[0].length) {
182+
flow.flowToAtlanticOcean = true;
183+
return;
184+
}
185+
186+
if (heights[i][j] == -1 || heights[i][j] > prev || flow.flowToAtlanticOcean && flow.flowToPacificOcean) {
187+
return;
188+
}
189+
190+
int currentHeight = heights[i][j];
191+
heights[i][j] = -1;
192+
193+
dfs(flow, heights, currentHeight, i + 1, j);
194+
dfs(flow, heights, currentHeight, i - 1, j);
195+
dfs(flow, heights, currentHeight, i, j + 1);
196+
dfs(flow, heights, currentHeight, i, j - 1);
197+
198+
heights[i][j] = currentHeight;
199+
}
200+
}
201+
202+
class Flow {
203+
boolean flowToPacificOcean;
204+
boolean flowToAtlanticOcean;
205+
}
206+
```
207+
208+
### TC, SC
209+
210+
heights의 길이를 `w`, heights[0]의 길이를 `h`로 정의했을 때,
211+
이 코드의 시간 복잡도는 `O((w \* h)^2)`, 공간 복잡도는 `O(w \* h)` 이다.
212+
시간 복잡도가 저렇게 나온 이유는 모든 좌표에 대해서 dfs를 진행하기 때문이다.

0 commit comments

Comments
 (0)