Long but modular Python solution


  • 0
    H

    I split up the problem into some other methods. I simply check what is on the left, right, top and bottom and if the cell has 1, add 1 appropriately. Comments appreciated.

    class Solution:
        @staticmethod
        def check_above(grid, index1, index2):
            if index1 == 0:
                return 1
            elif grid[index1-1][index2] == 0:
                return 1
            else:
                return 0
    
        def check_below(grid, index1, index2, size1):
            if index1 == size1 - 1:
                return 1
            elif grid[index1+1][index2] == 0:
                return 1
            else:
                return 0
    
        def check_left(grid, index1, index2):
            if index2 == 0:
                return 1
            elif grid[index1][index2-1] == 0:
                return 1
            else:
                return 0
    
        def check_right(grid, index1, index2, size2):
            if index2 == size2 - 1:
                return 1
            elif grid[index1][index2+1] == 0:
                return 1
            else:
                return 0
    
        @staticmethod
        def check_around(grid, index1, index2, size1, size2):
            perimeter = 0
            perimeter += Solution.check_above(grid, index1, index2)
            perimeter += Solution.check_below(grid, index1, index2, size1)
            perimeter += Solution.check_left(grid, index1, index2)
            perimeter += Solution.check_right(grid, index1, index2, size2)
    
            return perimeter
    
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            perimeter = 0
            size1 = len(grid)
            size2 = len(grid[0])
    
            for index1, row in enumerate(grid):
                for index2, cell in enumerate(row):
                    if cell == 1:
                        perimeter += self.check_around(grid, index1, index2, size1, size2)
    
            return perimeter
    
    
    
    
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.