Python solution, beats 99.65%

  • 0
    rst = 0
    for g in (grid, zip(*grid)):
        for row in g:
            tmp = 0
            for num in row:
                if num == 1:
                    tmp = 2
                elif tmp == 2 : #  and num == 0
                    rst += 2
                    tmp = 0
            rst += tmp
    return rst

    the basic idea is, in one row, every independent island (continuous '1's is one island) has one left side and one right side, then add 2 to the perimeter.

    iterate the grid list from left to right, and top to bottom, then you will get the perimeter.

Log in to reply

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