dfs
func maxAreaOfIsland(_ grid: [[Int]]) -> Int {
let row = grid.count
let col = grid.first!.count
var res = 0
var count = 0
var temp = grid
for i in 0..<row {
for j in 0..<col {
count = 0
dfs(&temp,i, j, row, col,&count,&res)
}
}
return res
}
func dfs(_ grid: inout [[Int]], _ i:Int,_ j:Int, _ row:Int,_ col:Int,_ count:inout Int, _ res: inout Int){
if i < 0 || j >= col || i >= row || j < 0 {
return
}
if grid[i][j] != 1 {
return
}
grid[i][j] = -1
count += 1
res = max(res, count)
//向右
dfs(&grid, i, j + 1, row, col,&count, &res)
//向左
dfs(&grid, i, j - 1, row, col,&count,&res)
//往下
dfs(&grid, i + 1, j , row, col,&count,&res)
//往上
dfs(&grid, i - 1, j , row, col,&count,&res)
}
网友评论