Suppose we have a binary matrix where 0 shows empty cell and 1 shows a block that forms a shape, now we have to find the perimeter of the shape. The shape will not hold any hole inside it.
So, if the input is like
0 | 0 | 0 | 0 | 0 |
0 | 0 | 1 | 1 | 1 |
0 | 0 | 1 | 1 | 0 |
0 | 1 | 1 | 1 | 0 |
0 | 0 | 0 | 0 | 0 |
then the output will be 14.
To solve this, we will follow these steps −
d := 0
perimeter := 0
height := row count of matrix
length := column count of matrix
for each row in matrix, do
c := 0
for each val in row, do
if val is same as 1, then
surround := 4
if c is not same as length - 1, then
if matrix[d, c + 1] is same as 1, then
surround := surround - 1
if c is not same as 0, then
if matrix[d, c - 1] is same as 1, then
surround := surround - 1
if d is not same as height - 1, then
if matrix[d + 1, c] is same as 1, then
surround := surround - 1
if d is not same as 0, then
if matrix[d - 1, c] is same as 1, then
surround := surround - 1
perimeter := perimeter + surround
c := c + 1
d := d + 1
return perimeter
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): d = 0 perimeter = 0 height = len(matrix) length = len(matrix[0]) for line in matrix: c = 0 for val in line: if val == 1: surround = 4 if c != length - 1: if matrix[d][c + 1] == 1: surround -= 1 if c != 0: if matrix[d][c - 1] == 1: surround -= 1 if d != height - 1: if matrix[d + 1][c] == 1: surround -= 1 if d != 0: if matrix[d - 1][c] == 1: surround -= 1 perimeter += surround c += 1 d += 1 return perimeter ob = Solution() matrix = [ [0,0,0,0,0], [0,0,1,1,1], [0,0,1,1,0], [0,1,1,1,0], [0,0,0,0,0] ] print(ob.solve(matrix))
Input
matrix = [ [0,0,0,0,0], [0,0,1,1,1], [0,0,1,1,0], [0,1,1,1,0], [0,0,0,0,0]]
Output
14