Skip to content

Commit da846a4

Browse files
committed
BFS 추가
1 parent a5e742a commit da846a4

File tree

1 file changed

+66
-1
lines changed

1 file changed

+66
-1
lines changed

pacific-atlantic-water-flow/sonjh1217.swift

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,71 @@
11
class Solution {
22
// O(m*n) time / O(m*n) space
3-
func pacificAtlantic(_ heights: [[Int]]) -> [[Int]] {
3+
func pacificAtlanticBFS(_ heights: [[Int]]) -> [[Int]] {
4+
var result = [[Int]]()
5+
guard let first = heights.first else {
6+
return result
7+
}
8+
let m = heights.count
9+
let n = first.count
10+
11+
var goesPacific = Array(repeating: Array(repeating: false, count: n), count: m)
12+
var goesAtlantic = Array(repeating: Array(repeating: false, count: n), count: m)
13+
let directions = [(1,0), (-1,0), (0,1), (0,-1)]
14+
15+
func bfs(queue: [(Int, Int)], goes: inout [[Bool]]) {
16+
var queue = queue
17+
var head = 0
18+
for (i, j) in queue {
19+
goes[i][j] = true
20+
}
21+
22+
while head < queue.count {
23+
var (i, j) = queue[head]
24+
head += 1
25+
26+
for (di, dj) in directions {
27+
let ni = i + di
28+
let nj = j + dj
29+
if ni >= 0
30+
&& ni < m
31+
&& nj >= 0
32+
&& nj < n
33+
&& !goes[ni][nj]
34+
&& heights[ni][nj] >= heights[i][j] {
35+
goes[ni][nj] = true
36+
queue.append((ni, nj))
37+
}
38+
}
39+
}
40+
}
41+
42+
var pacificStarts = [(Int, Int)]()
43+
var atlanticStarts = [(Int, Int)]()
44+
for i in 0..<m {
45+
pacificStarts.append((i, 0))
46+
atlanticStarts.append((i, n-1))
47+
}
48+
49+
for j in 0..<n {
50+
pacificStarts.append((0, j))
51+
atlanticStarts.append((m-1, j))
52+
}
53+
54+
bfs(queue: pacificStarts, goes: &goesPacific)
55+
bfs(queue: atlanticStarts, goes: &goesAtlantic)
56+
57+
for i in 0..<m {
58+
for j in 0..<n {
59+
if goesPacific[i][j] && goesAtlantic[i][j] {
60+
result.append([i, j])
61+
}
62+
}
63+
}
64+
return result
65+
}
66+
67+
// O(m*n) time / O(m*n) space
68+
func pacificAtlanticDFS(_ heights: [[Int]]) -> [[Int]] {
469
var result = [[Int]]()
570
guard let first = heights.first else {
671
return result

0 commit comments

Comments
 (0)