|
| 1 | +/** |
| 2 | + * Question Link: https://leetcode.com/problems/number-of-closed-islands/ |
| 3 | + * Primary idea: Classic Depth-first Search, go up, down, left, right four directions. Return false only it hits the edge. |
| 4 | + * |
| 5 | + * Time Complexity: O(mn), Space Complexity: O(mn) |
| 6 | + * |
| 7 | + */ |
| 8 | + |
| 9 | +class NumberClosedIslands { |
| 10 | + func closedIsland(_ grid: [[Int]]) -> Int { |
| 11 | + let m = grid.count, n = grid[0].count |
| 12 | + |
| 13 | + var isVisited = Array(repeating: Array(repeating: false, count: n), count: m), res = 0 |
| 14 | + |
| 15 | + for i in 0..<m { |
| 16 | + for j in 0..<n { |
| 17 | + guard !isVisited[i][j], grid[i][j] == 0 else { |
| 18 | + continue |
| 19 | + } |
| 20 | + |
| 21 | + if dfs(grid, i, j, m, n, &isVisited) { |
| 22 | + res += 1 |
| 23 | + } |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + return res |
| 28 | + } |
| 29 | + |
| 30 | + private func dfs(_ grid: [[Int]], _ i: Int, _ j: Int, _ m: Int, _ n: Int, _ isVisited: inout [[Bool]]) -> Bool { |
| 31 | + guard i >= 0 && i < m && j >= 0 && j < n else { |
| 32 | + return false |
| 33 | + } |
| 34 | + |
| 35 | + if grid[i][j] == 1 { |
| 36 | + return true |
| 37 | + } |
| 38 | + |
| 39 | + isVisited[i][j] = true |
| 40 | + |
| 41 | + |
| 42 | + var up = true, down = true, left = true, right = true |
| 43 | + |
| 44 | + if i - 1 < 0 || !isVisited[i - 1][j] { |
| 45 | + up = dfs(grid, i - 1, j, m, n, &isVisited) |
| 46 | + } |
| 47 | + if i + 1 >= m || !isVisited[i + 1][j] { |
| 48 | + down = dfs(grid, i + 1, j, m, n, &isVisited) |
| 49 | + } |
| 50 | + if j - 1 < 0 || !isVisited[i][j - 1] { |
| 51 | + left = dfs(grid, i, j - 1, m, n, &isVisited) |
| 52 | + } |
| 53 | + if j + 1 >= n || !isVisited[i][j + 1] { |
| 54 | + right = dfs(grid, i, j + 1, m, n, &isVisited) |
| 55 | + } |
| 56 | + |
| 57 | + return up && down && left && right |
| 58 | + } |
| 59 | +} |
0 commit comments