Island Perimeter LeetCode Solution



Quoestion:
ClickHere



Approach:

if value in the box is 1 then add 4 to result and check for adjacent boxes if they are also 1 if yes then decrement 2 in the result.because boxes connect using the perimeter and each box contibutes 1 so we reduce 1 + 1 in the result.

                                    

0          1
11 
0
1 


Algorithm:

1.Intialize res variable
2.Loop from i:1 to rows
    .loop from j:1 to columns
        .if grid[i][j] =1 then,
            .res= res +  4
            .if i >0 and grid[i-1][j]=1 then,
                .res= res- 2
            .if j >0 and grid[i][j-1]=1 then,
                .res= res- 2
3.return res

Python Code:

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

Shortened Python Code:

class Solution(object):
    def islandPerimeter(self, g):
        res = 0
        for i, p in enumerate(g):
            for j, q in enumerate(p):
                if q: 
                    res += 4                
                    if i > 0 and g[i-1][j]: res -= 2
                    if j > 0 and g[i][j-1]: res -= 2                                    
        return res




Post a Comment

0 Comments