forked from neetcode-gh/leetcode
- Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0200-number-of-islands.swift
58 lines (47 loc) · 1.78 KB
/
0200-number-of-islands.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
classSolution{
func numIslands(_ grid:[[Character]])->Int{
letROWS= grid.count
letCOLS=grid[0].count
varvisited=[[Bool]](
repeating:[Bool](repeating:false, count: COLS),
count: ROWS
)
varcount:Int=0
// Helper function to check if is within
func isWithin(row:Int, col:Int)->Bool{
return(
(row >=0) && (col >=0) &&
(row < ROWS) && (col < COLS)
)
}
// Helper function to check if cell is land or not
func isLand(row:Int, col:Int)->Bool{
returngrid[row][col]=="1"
}
letmovementsX=[-1,1,0,0]
letmovementsY=[0,0,-1,1]
// Helper DFS function to 'visit' the grid
func dfs(row:Int, col:Int){
// visit each child
for(dirX, dirY)inzip(movementsX, movementsY){
letrowNew= row + dirX
letcolNew= col + dirY
guardisWithin(row: rowNew, col: colNew)else{continue}
guardvisited[rowNew][colNew]==falseelse{continue}
guardisLand(row: rowNew, col: colNew)else{continue}
visited[rowNew][colNew]=true
dfs(row: rowNew, col: colNew)
}
}
forrin0..<ROWS {
forcin0..<COLS {
guardvisited[r][c]==falseelse{continue}
guardisLand(row: r, col: c)else{continue}
visited[r][c]=true
dfs(row: r, col: c)
count +=1
}
}
return count
}
}