File tree Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Expand file tree Collapse file tree 1 file changed +41
-0
lines changed Original file line number Diff line number Diff line change
1
+ class Solution {
2
+ fun closedIsland(grid: Array<IntArray>): Int {
3
+ val rows = grid.size
4
+ val cols = grid[0].size
5
+
6
+ val visited = Array(rows){BooleanArray(cols)}
7
+
8
+ fun isValid(r: Int, c: Int) = r in (0 until rows) && c in (0 until cols)
9
+
10
+ fun dfs(r: Int, c: Int): Int {
11
+ if(!isValid(r, c))
12
+ return 0
13
+ if(grid[r][c] == 1 || visited[r][c] == true)
14
+ return 1
15
+
16
+ visited[r][c] = true
17
+ return minOf(
18
+ minOf(
19
+ dfs(r + 1, c),
20
+ dfs(r - 1, c)
21
+ ),
22
+ minOf(
23
+ dfs(r, c + 1),
24
+ dfs(r, c - 1)
25
+ )
26
+ )
27
+ }
28
+
29
+ var islands = 0
30
+ for (r in 0 until rows) {
31
+ for (c in 0 until cols) {
32
+ if (grid[r][c] == 0 && visited[r][c] == false) {
33
+ if (dfs(r, c) != 0)
34
+ islands++
35
+ }
36
+ }
37
+ }
38
+
39
+ return islands
40
+ }
41
+ }
You can’t perform that action at this time.
0 commit comments