
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to find number of square submatrices with 1 in python
Suppose we have a 2D binary matrix, we have to find the total number of square submatrices with all 1 s are there.
So, if the input is like
1 | 1 | 1 | 0 |
1 | 1 | 1 | 0 |
1 | 1 | 1 | 0 |
0 | 0 | 0 | 0 |
1 | 0 | 1 | 1 |
then the output will be 17 as there are 12 (1 x 1) squares, 4 (2 x 2) squares and 1 (3 x 3) square.
To solve this, we will follow these steps −
- res := 0
- for i in range 0 to row count of matrix, do
- for j in range 0 to column count of matrix, do
- if i is same as 0 or j is same as 0, then
- res := res + matrix[i, j]
- otherwise when matrix[i, j] is same as 1, then
- matrix[i, j] = minimum of (matrix[i, j - 1], matrix[i - 1, j] and matrix[i - 1, j - 1]) + 1
- res := res + matrix[i, j]
- if i is same as 0 or j is same as 0, then
- for j in range 0 to column count of matrix, do
- return res
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, matrix): res = 0 for i in range(len(matrix)): for j in range(len(matrix[0])): if i == 0 or j == 0: res += matrix[i][j] elif matrix[i][j] == 1: matrix[i][j] = min(matrix[i][j - 1], matrix[i - 1][j], matrix[i - 1][j - 1]) + 1 res += matrix[i][j] return res ob = Solution() matrix = [ [1, 1, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0], [0, 0, 0, 0], [1, 0, 1, 1] ] print(ob.solve(matrix))
Input
matrix = [ [1, 1, 1, 0], [1, 1, 1, 0], [1, 1, 1, 0], [0, 0, 0, 0], [1, 0, 1, 1] ]
Output
17
- Related Questions & Answers
- Program to count number of square submatrices with all ones using Python
- Program to count number of square submatrices in given binary matrix in Python
- Count Square Submatrices with All Ones in C++
- Demlo number, Square of 11...1 in C++ Program
- Program to find out the number of non-zero submatrices in C++
- Program to Find Out the Minimal Submatrices in Python
- Program to find number of bit 1 in the given number in Python
- Program to count submatrices with all ones using Python
- 8085 program to find square root of a number
- 8086 program to find Square Root of a number
- 8086 program to find the square root of a perfect square root number
- 8085 program to find square of a 8 bit number
- Program to find number of rectangles that can form the largest square in Python
- Python program using map function to find row with maximum number of 1's
- Demlo number (Square of 11...1)” in C++?
Advertisements