[swift] LeetCode 695. Max Area of Island

栏目: Swift · 发布时间: 7年前

内容简介:Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.Find the maximum area of an island in the

Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water.

Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.)

Example 1:

[[0,0,1,0,0,0,0,1,0,0,0,0,0],

[0,0,0,0,0,0,0,1,1,1,0,0,0],

[0,1,1,0,1,0,0,0,0,0,0,0,0],

[0,1,0,0,1,1,0,0,1,0,1,0,0],

[0,1,0,0,1,1,0,0,1,1,1,0,0],

[0,0,0,0,0,0,0,0,0,0,1,0,0],

[0,0,0,0,0,0,0,1,1,1,0,0,0],

[0,0,0,0,0,0,0,1,1,0,0,0,0]]

Given the above grid, return 6. Note the answer is not 11, because the island must be connected 4-directionally.

Example 2:

[[0,0,0,0,0,0,0,0]]

Given the above grid, return 0.

Note: The length of each dimension in the given grid does not exceed 50.

func maxAreaOfIsland(_ grid: [[Int]]) -> Int {
    var i = 0, j = 0, v = 0
    var g = grid
    while i < grid.count {
        while j < grid[i].count {
            v = max(area(&g, i, j), v)
            j += 1
        }
        i += 1; j = 0
    }
    return v
}
 
private func area(_ g: inout [[Int]], _ i: Int, _ j: Int) -> Int {
    var v = 0
    if i < 0 || i >= g.count || j < 0 || j >= g[i].count {
        return 0
    }
    if g[i][j] == 1 {
        g[i][j] = 0; v = 1
        v += area(&g, i, j+1)
        v += area(&g, i+1, j)
        v += area(&g, i-1, j)
        v += area(&g, i, j-1)
    }
    return v
}
[swift] LeetCode 695. Max Area of Island [swift] LeetCode 695. Max Area of Island

(随着网站访问量的激增,服务器配置只得一再升级以维持网站不“404 Not Found”,所以网站的维护费用也在不断上涨……(目前的阿里云服务器ECS+云数据库RDS+域名购买+七牛云的费用是2200元/年),为了能不放弃该网站,所以我又把打赏链接放上来啦~所有打赏金额都会被记账并投入博客维护中,感谢厚爱,多多关照~)


以上所述就是小编给大家介绍的《[swift] LeetCode 695. Max Area of Island》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

算法笔记上机训练实战指南

算法笔记上机训练实战指南

胡凡、曾磊 / 机械工业出版社 / 2016-7 / 57

《算法笔记上机训练实战指南》是《算法笔记》的配套习题集,内容按照《算法笔记》的章节顺序进行编排,其中整理归类了PAT甲级、乙级共150多道题的详细题解,大部分题解均编有题意、样例解释、思路、注意点、参考代码,且代码中包含了详细的注释。读者可以通过本书对《算法笔记》的知识点进行更深入的学习和理解。书中印有大量二维码,用以实时更新或补充书籍的内容及发布本书的勘误。 《算法笔记上机训练实战指南》可......一起来看看 《算法笔记上机训练实战指南》 这本书的介绍吧!

SHA 加密
SHA 加密

SHA 加密工具

正则表达式在线测试
正则表达式在线测试

正则表达式在线测试

HEX HSV 转换工具
HEX HSV 转换工具

HEX HSV 互换工具