More than 1 year has passed since last update.
func numIslands(_ grids: [[Character]]) -> Int {
if grids.isEmpty || grids[0].isEmpty {
return 0
}
var count = 0
var grids = grids
for i in 0..<grids.count {
for j in 0..<grids[0].count {
if grids[i][j] == "1" {
count += 1
helper(&grids, i, j)
}
}
}
return count
}
private func helper(_ grids: inout [[Character]], _ x: Int, _ y: Int) {
guard x >= 0 && x < grids.count && y >= 0 && y < grids[0].count else {
return
}
if grids[x][y] == "1" {
grids[x][y] = "X"
helper(&grids, x-1, y)
helper(&grids, x+1, y)
helper(&grids, x, y-1)
helper(&grids, x, y+1)
}
}
Why not register and get more from Qiita?
- We will deliver articles that match you
By following users and tags, you can catch up information on technical fields that you are interested in as a whole
- you can read useful information later efficiently
By "stocking" the articles you like, you can search right away
Sign upLogin