Created
April 17, 2020 07:29
-
-
Save RP-3/5154c92ae375ca2203100c633d534523 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Solution { | |
func isVisited(_ grid: [[Character]], _ i: Int, _ j: Int) -> Bool { | |
return grid[i][j] == Character("2") | |
} | |
func markVisited(_ grid: inout [[Character]], _ i: Int, _ j: Int) { | |
guard i >= 0, j >= 0, i < grid.count, j < grid[i].count, !isVisited(grid, i, j), grid[i][j] == "1" else { | |
return | |
} | |
grid[i][j] = Character("2") | |
markVisited(&grid, i-1, j) | |
markVisited(&grid, i, j-1) | |
markVisited(&grid, i+1, j) | |
markVisited(&grid, i, j+1) | |
} | |
func numIslands(_ grid: [[Character]]) -> Int { | |
var numIslands = 0 | |
var grid = grid | |
for i in (0..<grid.count) { | |
for j in (0..<grid[i].count) { | |
guard !isVisited(grid, i, j) else { | |
continue | |
} | |
if grid[i][j] == "1" { | |
numIslands += 1 | |
markVisited(&grid, i, j) | |
} | |
} | |
} | |
return numIslands | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment