463.Island Perimeter

Link: https://leetcode.com/problems/island-perimeter/?tab=Description

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
Explanation: The perimeter is the 16 yellow stripes in the image below:


Solution:

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        if not grid:
            return 0

        num_of_rows = len(grid)
        num_of_cols = len(grid[0])

        perimeter = 0
        for row in xrange(num_of_rows):
            for col in xrange(num_of_cols):
                cell = grid[row][col]
                if not cell:
                    continue

                perimeter += 1 * self.get_num_of_exposed_edges(grid, num_of_rows, num_of_cols, row, col)

        return perimeter

    def get_num_of_exposed_edges(self, grid, num_of_rows, num_of_cols, curr_row, curr_col):

        # iterate four directions for this island.
        exposed_edges_counter = 0

        # top
        if curr_row - 1 < 0 or not grid[curr_row - 1][curr_col]:
            exposed_edges_counter += 1
        # right
        if curr_col + 1 >= num_of_cols or not grid[curr_row][curr_col + 1]:
            exposed_edges_counter += 1
        # bottom
        if curr_row + 1 >= num_of_rows or not grid[curr_row + 1][curr_col]:
            exposed_edges_counter += 1
        # left
        if curr_col - 1 < 0 or not grid[curr_row][curr_col - 1]:
            exposed_edges_counter += 1

        return exposed_edges_counter

Note:

  • Time complexity = O(n*m), n is the number of the rows in the given grid, m is the number of the columns in the given grid.

results matching ""

    No results matching ""