【leetcode】463. Island Perimeter【E】

来源:互联网 发布:虚拟机上装linux 编辑:程序博客网 时间:2024/04/29 19:26

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]]Answer: 16Explanation: The perimeter is the 16 yellow stripes in the image below:

Subscribe to see which companies asked this question



算法很简单,其实就是一共多少个1 ,乘以4就是一共有多少条边,然后再看有多少个相邻的边,每条相邻的边,减2,就对了

比如上面这个图,一共7个1 ,共28条边,6条相邻的边,28-12 = 16




class Solution(object):    def islandPerimeter(self, grid):                res = 0                for i in grid:            res += sum(i)        g= grid        res *= 4                i,j = 0,0                while i < len(g):            j = 0            while j < len(g[0]):                if j + 1< len(g[0]) and g[i][j] == 1 and g[i][j+1] == 1:                    res -= 2                j += 1            i += 1                    i,j = 0,0        while i < len(g[0]):            j = 0            while j < len(g):                if j + 1 < len(g) and g[j][i] == 1 and g[j+1][i] == 1:                    res -= 2                j += 1            i += 1        return res    


0 0