Leetcode-463. Island Perimeter

—Easy

https://leetcode.com/problems/island-perimeter/   

Leetcode-463. Island Perimeter_第1张图片

Code:

 

class Solution:
    def islandPerimeter(self, grid) :
        sum_count = 0
        if len(grid) == 0:
            return 0
        m = len(grid)
        n = len(grid[0])
        #print(m,n)
        for i in range(0,m):
            for j in range(0,n):
                if grid[i][j] == 1:
                    if ((i-1)>=0):
                        if grid[i-1][j] == 0:
                            sum_count += 1
                    else:
                        sum_count += 1
                    if (i+1) < m:
                        if grid[i+1][j] == 0:
                            sum_count += 1
                    else:
                        sum_count += 1
                    if (j-1)>=0:
                        if grid[i][j-1] == 0:
                            sum_count += 1
                    else:
                        sum_count += 1
                    if (j+1) < n:
                        if grid[i][j+1] == 0:
                            sum_count += 1
                    else:
                        sum_count += 1
        return sum_count


#test
#s=Solution()
#print(s.islandPerimeter([[0,1,0,0],[1,1,1,0], [0,1,0,0], [1,1,0,0]]))

思路:

1.核心就是遍历,遍历是可以采用不同的方法,第一种如代码:遍历当前格子与周围所有格子的关系,边遍历边计算;第二种方法:遍历时统计不同格子总数和重复边数,最后进行一个减法

2.以前做的oj上的题都考虑了输入的格式、大小的问题,这种面向对象的class编程好像能很巧妙地处理这个问题,比如如果我用c++或者Python来写,我都会首先考虑要开一个多大的空间来存储,现在就不用考虑这个问题了

你可能感兴趣的:(Leetcode)