text: We can count all 1 in the grid (cnt), and then find all continuous one in x axis and y axis (dec). The perimeter is just 4cnt - 2dec.
  def islandPerimeter(self, grid): """ :type grid: List[List[int]] :rtype: int """ if not grid: return 0 width = len(grid[0]) height = len(grid) cnt = 0 dec = 0 for i in xrange(0, height): for j in xrange(0, width): if grid[i][j] == 1: cnt += 1 if j != width - 1 and grid[i][j+1] == 1: dec += 1 #continuous 1 in x axis if i != height -1 and grid[i+1][j] == 1: dec += 1 #continuous 1 in y axis return 4*cnt - 2*dec