forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
1020-number-of-enclaves.kt
52 lines (42 loc) · 1.3 KB
/
1020-number-of-enclaves.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
42
43
44
45
46
47
48
49
50
51
52
class Solution {
fun numEnclaves(grid: Array<IntArray>): Int {
val rows = grid.size
val cols = grid[0].size
val dirs = arrayOf(
intArrayOf(1, 0),
intArrayOf(-1, 0),
intArrayOf(0, 1),
intArrayOf(0, -1)
)
val visited = Array(rows){BooleanArray(cols)}
fun isValid(r: Int, c: Int) =
r in (0 until rows) &&
c in (0 until cols) &&
visited[r][c] == false &&
grid[r][c] == 1
fun isValidBorder(r: Int, c: Int) =
(r == 0 || r == rows - 1 || c == 0 || c == cols - 1) &&
visited[r][c] == false
fun dfs(r: Int, c: Int): Int {
if (!isValid(r, c))
return 0
visited[r][c] = true
var res = 1
for ((dr, dc) in dirs) {
res += dfs(r + dr, c + dc)
}
return res
}
var totalLand = 0
var borderLand = 0
for (r in 0 until rows) {
for (c in 0 until cols) {
totalLand += grid[r][c]
if (grid[r][c] == 1 && isValidBorder(r, c)) {
borderLand += dfs(r, c)
}
}
}
return totalLand - borderLand
}
}