【leetcode】463. Island Perimeter【E】

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: 16
Explanation: 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    


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章