Island Perimeter

easy array matrix dfs

Problem

You are given row-by-row a grid where 1 is land and 0 is water. There is exactly one island (a 4-connected group of 1s). Return the perimeter of the island.

Inputgrid = [[0,1,0,0],[1,1,1,0],[0,1,0,0],[1,1,0,0]]
Output16
Each land cell contributes 4, minus 2 for each shared edge with another land cell.

def island_perimeter(grid):
    rows, cols = len(grid), len(grid[0])
    p = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == 1:
                p += 4
                if r > 0 and grid[r-1][c] == 1: p -= 2
                if c > 0 and grid[r][c-1] == 1: p -= 2
    return p
function islandPerimeter(grid) {
  const rows = grid.length, cols = grid[0].length;
  let p = 0;
  for (let r = 0; r < rows; r++) {
    for (let c = 0; c < cols; c++) {
      if (grid[r][c] === 1) {
        p += 4;
        if (r > 0 && grid[r-1][c] === 1) p -= 2;
        if (c > 0 && grid[r][c-1] === 1) p -= 2;
      }
    }
  }
  return p;
}
class Solution {
    public int islandPerimeter(int[][] grid) {
        int rows = grid.length, cols = grid[0].length, p = 0;
        for (int r = 0; r < rows; r++) {
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] == 1) {
                    p += 4;
                    if (r > 0 && grid[r-1][c] == 1) p -= 2;
                    if (c > 0 && grid[r][c-1] == 1) p -= 2;
                }
            }
        }
        return p;
    }
}
int islandPerimeter(vector<vector<int>>& grid) {
    int rows = grid.size(), cols = grid[0].size(), p = 0;
    for (int r = 0; r < rows; r++) {
        for (int c = 0; c < cols; c++) {
            if (grid[r][c] == 1) {
                p += 4;
                if (r > 0 && grid[r-1][c] == 1) p -= 2;
                if (c > 0 && grid[r][c-1] == 1) p -= 2;
            }
        }
    }
    return p;
}
Time: O(R · C) Space: O(1)