VOOZH about

URL: https://www.geeksforgeeks.org/dsa/find-perimeter-shapes-formed-1s-binary-matrix/

⇱ Find perimeter of shapes formed with 1s in binary matrix - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Find perimeter of shapes formed with 1s in binary matrix

Last Updated : 23 Jul, 2025

Given a matrix of N rows and M columns, consisting of 0's and 1's. The task is to find the perimeter of the subfigure consisting of only 1s in the matrix. The perimeter of a figure is given by the total number of horizontal and vertical linings formed by the boundary 1s of the subfigure. Each line is considered to have a length of 1 unit.
Note: There exists only one subfigure consisting of 1s

Examples:  

Input : mat[][] = {{1,0},{1,1}}
Output : 8
Explanation:

👁 Perimeter-Of-Shape-Formed-By-1S-1
Example 1

Input : mat[][] = {{0, 1, 0, 0, 0},{1, 1, 1, 0, 0},{1, 0, 0, 0, 0}}
Output : 12
Explanation:

👁 Perimeter-Of-Shape-Formed-By-1S
Example 2

Approach:

The idea is to traverse the matrix, find all ones and find their contribution in perimeter as per the below cases:

Case 1 (4 adjacent 1s) : contribution = 0
Case 2 (3 adjacent 1s) : contribution = 1
Case 3 (2 adjacent 1s) : contribution = 2
Case 4 (1 adjacent 1s) : contribution = 3
Case 5 (0 adjacent 1s) : contribution = 4

Finally return the sum of contribution of each 1 in the matrix as the answer.

  • Traverse the whole matrix and find the cell having value equal to 1.
  • Calculate the number of adjacent 1s for that cell and add, 4 - number of adjacent 1s to the total perimeter.

Below is the implementation of this approach: 


Output
12

Time Complexity: O(R x C).
Auxiliary Space: O(1), since no extra space has been taken.

Comment
Article Tags:
Article Tags: