
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Find Area of Largest Square of 1s in a Given Matrix in Python
Suppose we have a binary matrix, we have to find largest square of 1s in that given matrix.
So, if the input is like
1 |
0 |
0 |
0 |
0 |
1 |
1 |
0 |
0 |
0 |
0 |
0 |
1 |
1 |
0 |
1 |
1 |
1 |
1 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
0 |
0 |
0 |
1 |
1 |
1 |
1 |
0 |
0 |
then the output will be 16.
To solve this, we will follow these steps −
- res := 0
- for i in range 0 to size of matrix, do
- res := maximum of res and matrix[i, 0]
- for i in range 0 to size of matrix[0], do
- res := maximum of res and matrix[0, i]
- for i in range 1 to row count of matrix, do
- for j in range 1 to column count of matrix, do
- if matrix[i, j] is same as 1, then
- matrix[i, j] = minimum of (matrix[i - 1, j], matrix[i - 1, j - 1] and matrix[i, j - 1]) + 1
- res = maximum of res and matrix[i, j]
- if matrix[i, j] is same as 1, then
- for j in range 1 to column count of matrix, do
- return res^2
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)): res = max(res, matrix[i][0]) for i in range(len(matrix[0])): res = max(res, matrix[0][i]) for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i][j] == 1: matrix[i][j] = min(matrix[i - 1][j], matrix[i - 1][j - 1], matrix[i][j - 1]) + 1 res = max(res, matrix[i][j]) return res * res ob = Solution() matrix = [ [1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0] ] print(ob.solve(matrix))
Input
matrix = [ [1, 0, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 1, 1], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 0, 0] ]
Output
16
Advertisements