My Python Solution for Island Perimeter Problem


  • 0
    S
    class Solution(object):
        def islandPerimeter(self, grid):
            """
            :type grid: List[List[int]]
            :rtype: int
            """
            oneCounter = 0
            overlapCounter = 0
            perimeter = 0
            for i in range(0,len(grid)):
                for j in range(0,len(grid[i])):
                    if(grid[i][j] == 1):
                        oneCounter = oneCounter + 1
                        overlapCounter = overlapCounter + self.getNeighbourCount(grid,i,j,len(grid[i]))
            
            perimeter =  (oneCounter*4) - overlapCounter
            print("Perimeter: " + str(perimeter))
            return perimeter
        
        def getNeighbourCount(self, matrix,posx,posy,width):
            neighbourCount = 0
            if( (posy + 1) < width):
                if(matrix[posx][posy + 1] == 1):
                    neighbourCount = neighbourCount + 1
            
            if( (posy - 1) >= 0):
                if(matrix[posx][posy - 1] == 1):
                    neighbourCount = neighbourCount + 1
            
            if( (posx + 1) < len(matrix) ):
                if(matrix[posx + 1][posy] == 1):
                    neighbourCount = neighbourCount + 1
            
            if( (posx - 1) >= 0):
                if(matrix[posx - 1][posy] == 1):
                    neighbourCount = neighbourCount + 1
            
            return neighbourCount
            
        
    

Log in to reply
 

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