[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》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!

查看所有标签

猜你喜欢:

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

编程风格

编程风格

[美] Cristina Videira Lopes / 顾中磊 / 人民邮电出版社 / 2017-8 / 55.00元

本书对一个常见的编程问题定义了不同的约束,分别使用33种方法实现了同一个词频统计任务,从而形成了风格迥异的编程风格。作者以惯用的计算机语言与简单的任务为画笔,描绘了一次生动难忘的编程之旅,帮助读者加深了对语言的理解,也提供了崭新的编程思路。一起来看看 《编程风格》 这本书的介绍吧!

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具

RGB CMYK 转换工具
RGB CMYK 转换工具

RGB CMYK 互转工具

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具