forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
NumberofIslands.swift
44 lines (37 loc) · 1.14 KB
/
NumberofIslands.swift
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
/**
* Question Link: https://leetcode.com/problems/number-of-islands/
* Primary idea: Classic Depth-first Search, go up, down, left, right four directions
*
* Time Complexity: O(mn), Space Complexity: O(1)
*
*/
class NumberofIslands {
func numIslands(grid: [[Character]]) -> Int {
guard grid.count > 0 && grid[0].count > 0 else {
return 0
}
var grid = grid
let m = grid.count
let n = grid[0].count
var count = 0
for i in 0..<m {
for j in 0..<n {
if String(grid[i][j]) == "1" {
count += 1
_dfs(&grid, m, n, i, j)
}
}
}
return count
}
private func _dfs(inout grid: [[Character]], _ m: Int, _ n: Int, _ i: Int, _ j: Int) {
guard i >= 0 && i < m && j >= 0 && j < n && String(grid[i][j]) == "1" else {
return
}
grid[i][j] = Character("0")
_dfs(&grid, m, n, i + 1, j)
_dfs(&grid, m, n, i - 1, j)
_dfs(&grid, m, n, i, j + 1)
_dfs(&grid, m, n, i, j - 1)
}
}