Skip to content

Commit 1c02235

Browse files
committed
Solution Number of islands
1 parent cfd3c2c commit 1c02235

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

number-of-islands/doitduri.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
func numIslands(_ grid: [[Character]]) -> Int {
3+
guard !grid.isEmpty else { return 0 }
4+
5+
let rows = grid.count
6+
let colums = grid[0].count
7+
var visited = grid
8+
var islandCount = 0
9+
10+
func dfs(_ row: Int, _ col: Int) {
11+
guard row >= 0 && row < rows && col >= 0 && col < colums && visited[row][col] == "1" else {
12+
return
13+
}
14+
15+
visited[row][col] = "0"
16+
17+
dfs(row - 1, col)
18+
dfs(row + 1, col)
19+
dfs(row, col - 1)
20+
dfs(row, col + 1)
21+
}
22+
23+
for row in 0..<rows {
24+
for col in 0..<colums {
25+
if visited[row][col] == "1" {
26+
islandCount += 1
27+
dfs(row, col)
28+
}
29+
}
30+
}
31+
32+
return islandCount
33+
}
34+
}

0 commit comments

Comments
 (0)