Suppose we have m x n binary matrix, we have to find how many square submatrices have all ones.
So, if the input is like.
0 | 1 | 1 | 1 |
1 | 1 | 1 | 1 |
0 | 1 | 1 | 1 |
then the output will be 15, as there are 10 squares of side 1. 4 squares of side 2 and 1 square of side 3. Then total number of squares = 10 + 4 + 1 = 15.
To solve this, we will follow these steps −
if matrix has single one, then
return 1
rows := row count of matrix
cols := column count of matrix[0]
result := 0
for row in range 0 to rows - 1, do
for col in range 0 to cols - 1, do
if row is same as 0 or col is same as 0, then
if matrix[row, col] is same as 1, then
result := result + 1
otherwise when matrix[row, col] is same as 1, then
square := 1 + (minimum of matrix[row-1,col], matrix[row,col-1] and matrix[row-1,col-1])
matrix[row, col] := square
result := result + square
return result
Let us see the following implementation to get better understanding −
Example
def solve(matrix): if matrix == [[1]]: return 1 rows = len(matrix) cols = len(matrix[0]) result = 0 for row in range(rows): for col in range(cols): if (row == 0 or col == 0): if matrix[row][col] == 1: result += 1 elif matrix[row][col] == 1: square = min(matrix[row-1][col], min(matrix[row][col-1], matrix[row-1][col-1])) + 1 matrix[row][col] = square result += square return result matrix = [[0,1,1,1],[1,1,1,1],[0,1,1,1]] print(solve(matrix))
Input
{{0,1,1,1},{1,1,1,1},{0,1,1,1}}
Output
15