Skip to content
This repository was archived by the owner on Aug 14, 2024. It is now read-only.

Latest commit

 

History

History
58 lines (45 loc) · 1.77 KB

463.md

File metadata and controls

58 lines (45 loc) · 1.77 KB

463. Island Perimeter

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

Thinking Process

  1. Count the number of 1s in the table
  2. Count the number of neighors that is 1 for each cell has value 1 in the table
  3. Perimeter = 4 * total number of 1 cell - total number of neighbors that has value 1

Code

public class Solution {
    public int islandPerimeter(int[][] grid) {
        int res = 0;
        for(int i = 0; i < grid.length; i++){
            for(int j = 0; j < grid[0].length; j++){
                if(grid[i][j] == 1){
                    res += 4;
                    res -= numberOfNeighbors(grid, i, j);
                }
            }
        }
        return res;
    }
    
    int numberOfNeighbors(int[][] grid, int i, int j){
        int neighbors = 0;
        
        if(i > 0 && grid[i-1][j] == 1)
            neighbors++;
        if(j > 0 && grid[i][j-1] == 1)
            neighbors++;
        if(i < grid.length - 1 && grid[i+1][j] == 1)
            neighbors++;
        if(j < grid[0].length - 1 && grid[i][j+1] == 1)                   neighbors++;
        return neighbors;
    }  
}

Complexity

  1. Time complexity is O(mn), each cell may be visited upto 4 times