美文网首页
剑指 Offer II 105. 岛屿的最大面积

剑指 Offer II 105. 岛屿的最大面积

作者: 邦_ | 来源:发表于2022-08-12 09:29 被阅读0次

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)
  
        
    }







相关文章

网友评论

      本文标题:剑指 Offer II 105. 岛屿的最大面积

      本文链接:https://www.haomeiwen.com/subject/siqtgrtx.html