Python solution, easy to understand, beating over 95%


  • 1
    K

    Since the result would be number of islands×2+2 if there is no 2×2 islands and every 2×2 islands would reduce the result by 2, we can calculate the number of islands and the number of 2×2 islands to get the result.

        num=0
        for i in range(0,len(grid)):
            for j in range(0,len(grid[i])):
                if grid[i][j]==1:
                    num+=2
                    if i>0 and j>0:
                        if grid[i-1][j]==1 and grid[i][j-1]==1 and grid[i-1][j-1]==1:
                            num-=2
        return num+2

Log in to reply
 

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