LeetCode Island Perimeter
来源:互联网 发布:淘宝助手上传宝贝失败 编辑:程序博客网 时间:2024/05/16 11:53
You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island.
Example:
[[0,1,0,0],
[1,1,1,0],
[0,1,0,0],
[1,1,0,0]]
Explanation: The perimeter is the 16 yellow stripes in the image below
Answer: 16
思路很简单,每次看看上下左右的邻居是不是1,如果有一个是的话,就减一,都是一,自然而然对周长没有贡献,如果都不是一,那就是另一个极端,对周长贡献是4。
class Solution(object): def islandPerimeter(self, grid): """ :type grid: list[list[int]] :rtype: int """ r = 0 row = len(grid) column = len(grid[0]) for i in xrange(row): for j in xrange(column): if grid[i][j] == 1: count = 4 if 0 <= i - 1 < row and 0 <= j < column and grid[i - 1][j] == 1: count -= 1 if 0 <= i + 1 < row and 0 <= j < column and grid[i + 1][j] == 1: count -= 1 if 0 <= i < row and 0 <= j - 1 < column and grid[i][j - 1] == 1: count -= 1 if 0 <= i < row and 0 <= j + 1 < column and grid[i][j + 1] == 1: count -= 1 r += count return rif __name__ == '__main__': print Solution().islandPerimeter([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0], [1, 1, 0, 0]])
- leetcode 463. Island Perimeter
- [LeetCode]Island Perimeter -Python
- leetcode 463. Island Perimeter
- leetcode Island Perimeter
- Leetcode 463 Island Perimeter
- leetcode- Island Perimeter
- 【LeetCode】Island Perimeter
- LeetCode 463. Island Perimeter
- [leetcode 463]Island Perimeter
- [LeetCode-463]Island Perimeter
- Leetcode 463 Island Perimeter
- Leetcode Island Perimeter
- 【LeetCode】 463. Island Perimeter
- leetcode-463- Island Perimeter
- [leetcode]463. Island Perimeter
- Leetcode-463. Island Perimeter
- Leetcode 463. Island Perimeter
- 【Leetcode】463. Island Perimeter
- 日志级别之前增加自定义字段
- 前端flash视频插入
- Linux 学习总结 (三)
- Pascal's Triangle问题及解法
- VMware12中Ubuntu16.10问题汇总
- LeetCode Island Perimeter
- Android 多线程详解
- 初学linux ---linux文件结构及管理
- Linux 学习总结 (四)
- 微信公众号开发-自定义菜单中链接用MUI前端框架写的网页以及发布到SAE服务器
- 关于SearchView的使用理解
- Linux操作系统十个注意事项
- Android Studio 百度地图定位、轨迹及所在位置与标注marker的距离
- LeetCode Nim Game