Skip to content

Commit ad57e9b

Browse files
committed
Adding 200. Number of Islands in Swift
1 parent 8fa7d09 commit ad57e9b

File tree

1 file changed

+58
-0
lines changed

1 file changed

+58
-0
lines changed

swift/200-Number-of-Islands.swift

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
class Solution {
2+
3+
func numIslands(_ grid: [[Character]]) -> Int {
4+
let ROWS = grid.count
5+
let COLS = grid[0].count
6+
7+
var visited = [[Bool]](
8+
repeating: [Bool](repeating: false, count: COLS),
9+
count: ROWS
10+
)
11+
var count: Int = 0
12+
13+
// Helper function to check if is within
14+
func isWithin(row: Int, col: Int) -> Bool {
15+
return (
16+
(row >= 0) && (col >= 0) &&
17+
(row < ROWS) && (col < COLS)
18+
)
19+
}
20+
21+
// Helper function to check if cell is land or not
22+
func isLand(row: Int, col: Int) -> Bool {
23+
return grid[row][col] == "1"
24+
}
25+
26+
let movementsX = [-1, 1, 0, 0]
27+
let movementsY = [0, 0, -1, 1]
28+
29+
// Helper DFS function to 'visit' the grid
30+
func dfs(row: Int, col: Int) {
31+
// visit each child
32+
for (dirX, dirY) in zip(movementsX, movementsY) {
33+
let rowNew = row + dirX
34+
let colNew = col + dirY
35+
36+
guard isWithin(row: rowNew, col: colNew) else { continue }
37+
guard visited[rowNew][colNew] == false else { continue }
38+
guard isLand(row: rowNew, col: colNew) else { continue }
39+
40+
visited[rowNew][colNew] = true
41+
dfs(row: rowNew, col: colNew)
42+
}
43+
}
44+
45+
for r in 0..<ROWS {
46+
for c in 0..<COLS {
47+
guard visited[r][c] == false else { continue }
48+
guard isLand(row: r, col: c) else { continue }
49+
50+
visited[r][c] = true
51+
dfs(row: r, col: c)
52+
count += 1
53+
}
54+
}
55+
56+
return count
57+
}
58+
}

0 commit comments

Comments
 (0)