forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1254-number-of-closed-islands.kt
41 lines (35 loc) · 1.05 KB
/
1254-number-of-closed-islands.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
class Solution {
fun closedIsland(grid: Array<IntArray>): Int {
val rows = grid.size
val cols = grid[0].size
val visited = Array(rows){BooleanArray(cols)}
fun isValid(r: Int, c: Int) = r in (0 until rows) && c in (0 until cols)
fun dfs(r: Int, c: Int): Int {
if(!isValid(r, c))
return 0
if(grid[r][c] == 1 || visited[r][c] == true)
return 1
visited[r][c] = true
return minOf(
minOf(
dfs(r + 1, c),
dfs(r - 1, c)
),
minOf(
dfs(r, c + 1),
dfs(r, c - 1)
)
)
}
var islands = 0
for (r in 0 until rows) {
for (c in 0 until cols) {
if (grid[r][c] == 0 && visited[r][c] == false) {
if (dfs(r, c) != 0)
islands++
}
}
}
return islands
}
}