Header Ad

Leetcode Island Perimeter problem solution

In this Leetcode Island Perimeter problem solution You are given row x col grid representing a map where grid[i][j] = 1 represents land and grid[i][j] = 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", meaning the water inside 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.

Leetcode Island Perimeter problem solution

Problem solution in Python.

class Solution(object):
    def islandPerimeter(self, grid):
        """
        :type grid: List[List[int]]
        :rtype: int
        """
        ret = 0
        nrows = len(grid)
        ncols = len(grid[0])
        for i in range(nrows):
            ret += sum(grid[i])*4
            for j in range(ncols):
                if grid[i][j] == 1:
                    if j+1<ncols and grid[i][j+1] == 1:
                        ret -= 2
                    if i+1<nrows and grid[i+1][j] == 1:
                        ret -= 2
        return ret


Problem solution in Java.

class Solution {
    public int islandPerimeter(int[][] grid) {
        if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
        int R = grid.length, C = grid[0].length;
        int cellCount = 0, neighborCount = 0;
        for (int r = 0; r < R; ++r) {
            for (int c = 0; c < C; ++c) {
                if (grid[r][c] == 1) {
                    cellCount++;
                    // right, down
                    if (c < C-1 && grid[r][c+1] == 1) neighborCount++;
                    if (r < R-1 && grid[r+1][c] == 1) neighborCount++;
                }
            }
        }
        return cellCount * 4 - neighborCount * 2;
    }
}


Problem solution in C++.

class Solution {
public:
    int islandPerimeter(vector<vector<int>>& grid) {
        int res = 0;
        int m = grid.size();
        if(!m) return 0;
        int n = grid[0].size();
        if(!n) return 0;
        for(int i = 0; i < m; ++i)
        for(int j = 0; j < n; ++j)
           if(grid[i][j] == 1)
           {
               if(!j || grid[i][j-1] == 0)
                 ++res;
               if(!i || grid[i-1][j] == 0)
                 ++res;
               if(j == n-1 || grid[i][j+1] == 0)
                 ++res;
               if(i == m-1 || grid[i+1][j] == 0)
                 ++res;
           }
        return res;
        
    }
};

Post a Comment

0 Comments