Find perimeter of shapes formed with 1s in binary matrix

Last Updated : 2 Sep, 2026

Given a binary matrix mat[][] of size n * m, where each cell contains either 0 or 1, find the total perimeter of all the cells containing 1. Two cells are considered adjacent if they share a common side.

Note: A single cell containing 1 has a perimeter of 4, whereas two adjacent cells containing 1 (i.e., 11) together have a perimeter of 6.

Examples:  

Input: mat[][] = [[0,1,0,0,0], [1,1,1,0,0], [1,0,0,0,0]]
Output: 12
Explanation: The five cells form a single figure. Hence, the perimeter of the figure is 12.

Input: mat[][] = [[1,0], [1,1]]
Output: 8
Explanation: The two adjacent cells share one common side. Hence, the perimeter of the figure is 6.

Try It Yourself
redirect icon

[Expected Approach] Count the Exposed Sides of Each 1 - O(n * m) Time and O(1) Space

The idea is to visit every cell containing 1 and check its four sides. A side contributes to the perimeter only when it is not shared with another 1 cell.

Therefore, if a side is outside the matrix or adjacent to a 0, it contributes 1 to the perimeter. By counting all such exposed sides, we get the total perimeter.

Working of the Approach:

  • Traverse every cell of the matrix.
  • For each cell containing 1, check its four neighboring sides.
  • If a side is outside the matrix or the neighboring cell is 0, add 1 to the perimeter.
  • Return the total perimeter.
C++
#include <bits/stdc++.h>
using namespace std;

int findPerimeter(vector<vector<int>>& mat) {
    int n = mat.size();
    int m = mat[0].size();
    int perimeter = 0;

    int dr[] = {-1, 1, 0, 0};
    int dc[] = {0, 0, -1, 1};

    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (mat[i][j] == 0)
                continue;

            // Check all four sides of the current 1 cell.
            for (int d = 0; d < 4; d++) {
                int ni = i + dr[d];
                int nj = j + dc[d];

                // Count the side if it is exposed.
                if (ni < 0 || ni >= n || nj < 0 || nj >= m ||
                    mat[ni][nj] == 0) {
                    perimeter++;
                }
            }
        }
    }

    return perimeter;
}

int main() {
    vector<vector<int>> mat = {
        {1, 0},
        {1, 1}
    };

    cout << findPerimeter(mat);

    return 0;
}
Java
import java.util.*;

class GFG {

    static int findPerimeter(int[][] mat) {
        int n = mat.length;
        int m = mat[0].length;
        int perimeter = 0;

        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < m; j++) {
                if (mat[i][j] == 0)
                    continue;

                // Check all four sides of the current 1 cell.
                for (int d = 0; d < 4; d++) {
                    int ni = i + dr[d];
                    int nj = j + dc[d];

                    // Count the side if it is exposed.
                    if (ni < 0 || ni >= n || nj < 0 || nj >= m ||
                        mat[ni][nj] == 0) {
                        perimeter++;
                    }
                }
            }
        }

        return perimeter;
    }

    public static void main(String[] args) {
        int[][] mat = {
            {1, 0},
            {1, 1}
        };

        System.out.println(findPerimeter(mat));
    }
}
Python
def findPerimeter(mat):
    n = len(mat)
    m = len(mat[0])
    perimeter = 0

    directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

    for i in range(n):
        for j in range(m):
            if mat[i][j] == 0:
                continue

            # Check all four sides of the current 1 cell.
            for dr, dc in directions:
                ni = i + dr
                nj = j + dc

                # Count the side if it is exposed.
                if (ni < 0 or ni >= n or
                    nj < 0 or nj >= m or
                    mat[ni][nj] == 0):
                    perimeter += 1

    return perimeter


if __name__ == "__main__":
    mat = [
        [1, 0],
        [1, 1]
    ]

    print(findPerimeter(mat))
C#
using System;

class GFG
{
    static int findPerimeter(int[][] mat)
    {
        int n = mat.Length;
        int m = mat[0].Length;
        int perimeter = 0;

        int[] dr = {-1, 1, 0, 0};
        int[] dc = {0, 0, -1, 1};

        for (int i = 0; i < n; i++)
        {
            for (int j = 0; j < m; j++)
            {
                if (mat[i][j] == 0)
                    continue;

                // Check all four sides of the current 1 cell.
                for (int d = 0; d < 4; d++)
                {
                    int ni = i + dr[d];
                    int nj = j + dc[d];

                    // Count the side if it is exposed.
                    if (ni < 0 || ni >= n ||
                        nj < 0 || nj >= m ||
                        mat[ni][nj] == 0)
                    {
                        perimeter++;
                    }
                }
            }
        }

        return perimeter;
    }

    static void Main()
    {
        int[][] mat = {
            new int[] {1, 0},
            new int[] {1, 1}
        };

        Console.WriteLine(findPerimeter(mat));
    }
}
JavaScript
function findPerimeter(mat) {
    const n = mat.length;
    const m = mat[0].length;
    let perimeter = 0;

    const directions = [
        [-1, 0],
        [1, 0],
        [0, -1],
        [0, 1]
    ];

    for (let i = 0; i < n; i++) {
        for (let j = 0; j < m; j++) {
            if (mat[i][j] === 0)
                continue;

            // Check all four sides of the current 1 cell.
            for (const [dr, dc] of directions) {
                const ni = i + dr;
                const nj = j + dc;

                // Count the side if it is exposed.
                if (ni < 0 || ni >= n ||
                    nj < 0 || nj >= m ||
                    mat[ni][nj] === 0) {
                    perimeter++;
                }
            }
        }
    }

    return perimeter;
}

// Driver Code
const mat = [
    [1, 0],
    [1, 1]
];

console.log(findPerimeter(mat));

Output
8
Comment