LeetCode: Island Perimeter Posted on February 27, 2018July 26, 2020 by braindenny Island Perimeter Similar Problems: LeetCode: Regions Cut By Slashes Series: Island & Follow-up CheatSheet: Leetcode For Code Interview CheatSheet: Common Code Problems & Follow-ups Tag: #graph, #array, #island You are given a map in form of a two-dimensional integer grid where 1 represents land and 0 represents water. Grid cells are connected horizontally/vertically (not diagonally). The grid is completely surrounded by water, and there is exactly one island (i.e., one or more connected land cells). The island doesn’t have “lakes” (water inside that isn’t connected to the water around the island). One cell is a square with side length 1. The grid is rectangular, width and height don’t exceed 100. Determine the perimeter of the island. Example: [[0,1,0,0], [1,1,1,0], [0,1,0,0], [1,1,0,0]] Answer: 16 Github: code.dennyzhang.com Credits To: leetcode.com Leave me comments, if you have better ways to solve. Solution: array ## https://code.dennyzhang.com/island-perimeter ## Basic Ideas: array ## ## Add then substract ## ## Complexity: Time O(n*m), Space O(1) class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: cnt = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: cnt += 4 ## check below if i<len(grid)-1 and grid[i+1][j] == 1: cnt -= 2 ## check right if j<len(grid[0])-1 and grid[i][j+1] == 1: cnt -= 2 return cnt Solution: array ## https://code.dennyzhang.com/island-perimeter ## Basic Ideas: array ## ## Check each cell ## ## Complexity: Time O(n*m), Space O(1) class Solution: def islandPerimeter(self, grid: List[List[int]]) -> int: def check(i, j): res = 0 for i2, j2 in [(i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)]: if i2<0 or i2>=len(grid) or j2<0 or j2>=len(grid[0]) or grid[i2][j2] == 0: res += 1 return res cnt = 0 for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: cnt += check(i, j) return cnt Post Views: 5 Post navigation LeetCode: Largest Palindrome ProductLeetCode: Alien Dictionary Leave a Reply Cancel replyYour email address will not be published.Comment Name Email Website