python solution


  • 0
    S

    The perimeter is the sum of four edges,try to see the gird from four sides.
    from the left side, all the left edges of the island have two pattern:
    contains [0,1] or the first element is [1]
    look in this side->[[0,1,0,0],
    look in this side ->[1,1,1,0],
    look in this side->[0,1,0,0],
    look in this side ->[1,1,0,0]]

    step1: convert the list element to str type and connect to string.
    step2:calculate the occurrence times of ‘01’,and wether the first element is '1', the sum of it is the left side perimeter.
    step3:calculate the occurrence times of ‘10’,and wether the end element is '1', the sum of it is the right side perimeter.
    step4:transpose the grid and repeat step1~3 to calculate the top and bottom perimeter.
    here is the code:
    '''

        row_list=[]
        # convert the list element to str type and connect to string
        for each in grid:
            row_list.append("".join(list(map(str, each))))
        row = 0
        for each in row_list:
            # calculate the left side
            row += each.count('01')
            if each[0] == '1':
                row += 1
            # calculate the right side
            row += each.count('10')
            if each[-1] == '1':
                row += 1
        col_list = []
        # Transpose the gird
        r_grid = list(zip(*grid))
        for each in r_grid:
            col_list.append("".join(list(map(str, each))))
        col = 0
        for each in col_list:
            # calculate the top side
            col += each.count('01')
            if each[0] == '1':
                col += 1
            # calculate the bottom side
            col += each.count('10')
            if each[-1] == '1':
                col += 1
    
        return col + row
    

    '''


Log in to reply
 

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