Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python Program for Maximum and Minimum in a square matrix.
Next article icon

Python Program for Maximum size square sub-matrix with all 1s

Last Updated : 24 Oct, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

Write a Python program for a given binary matrix, the task is to find out the maximum size square sub-matrix with all 1s.

Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Approach:

Let the given binary matrix be M[R][C]. The idea of the algorithm is to construct an auxiliary size matrix S[][] in which each entry S[i][j] represents the size of the square sub-matrix with all 1s including M[i][j] where M[i][j] is the rightmost and bottom-most entry in sub-matrix.

Step-by-step approach:

  • Construct a sum matrix S[R][C] for the given M[R][C].
    • Copy first row and first columns as it is from M[][] to S[][]
    • For other entries, use the following expressions to construct S[][]
      • If M[i][j] is 1 then
        • S[i][j] = min(S[i][j-1], S[i-1][j], S[i-1][j-1]) + 1
      • Else If M[i][j] is 0 then
        • S[i][j] = 0
  • Find the maximum entry in S[R][C]
  • Using the value and coordinates of maximum entry in S[i], print sub-matrix of M[][]

Below is the implementation of the above approach:

Python3




# Python3 code for Maximum size
# square sub-matrix with all 1s
 
def printMaxSubSquare(M):
    R = len(M) # no. of rows in M[][]
    C = len(M[0]) # no. of columns in M[][]
 
    S = []
    for i in range(R):
        temp = []
        for j in range(C):
            if i == 0 or j == 0:
                temp += M[i][j],
            else:
                temp += 0,
        S += temp,
    # here we have set the first row and first column of S same as input matrix, other entries are set to 0
 
    # Update other entries
    for i in range(1, R):
        for j in range(1, C):
            if (M[i][j] == 1):
                S[i][j] = min(S[i][j-1], S[i-1][j],
                            S[i-1][j-1]) + 1
            else:
                S[i][j] = 0
 
    # Find the maximum entry and
    # indices of maximum entry in S[][]
    max_of_s = S[0][0]
    max_i = 0
    max_j = 0
    for i in range(R):
        for j in range(C):
            if (max_of_s < S[i][j]):
                max_of_s = S[i][j]
                max_i = i
                max_j = j
 
    print("Maximum size sub-matrix is: ")
    for i in range(max_i, max_i - max_of_s, -1):
        for j in range(max_j, max_j - max_of_s, -1):
            print(M[i][j], end=" ")
        print("")
 
 
# Driver Program
M = [[0, 1, 1, 0, 1],
    [1, 1, 0, 1, 0],
    [0, 1, 1, 1, 0],
    [1, 1, 1, 1, 0],
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 0]]
 
printMaxSubSquare(M)
 
# This code is contributed by Soumen Ghosh
 
 
Output
Maximum size sub-matrix is:  1 1 1  1 1 1  1 1 1  

Time Complexity: O(m*n), where m is the number of rows and n is the number of columns in the given matrix.
Auxiliary Space: O(m*n), where m is the number of rows and n is the number of columns in the given matrix.

Python Program for Maximum size square sub-matrix with all 1s using Dynamic Programming:

In order to compute an entry at any position in the matrix we only need the current row and the previous row.

Below is the implementation of the above approach:

Python3




# Python code for Maximum size square
# sub-matrix with all 1s
# (space optimized solution)
 
R = 6
C = 5
 
 
def printMaxSubSquare(M):
 
    global R, C
    Max = 0
 
    # set all elements of S to 0 first
    S = [[0 for col in range(C)]for row in range(2)]
 
    # Construct the entries
    for i in range(R):
        for j in range(C):
 
            # Compute the entrie at the current position
            Entrie = M[i][j]
            if(Entrie):
                if(j):
                    Entrie = 1 + min(S[1][j - 1], min(S[0][j - 1], S[1][j]))
 
            # Save the last entrie and add the new one
            S[0][j] = S[1][j]
            S[1][j] = Entrie
 
            # Keep track of the max square length
            Max = max(Max, Entrie)
 
    # Print the square
    print("Maximum size sub-matrix is: ")
    for i in range(Max):
        for j in range(Max):
            print("1", end=" ")
        print()
 
 
# Driver code
M = [[0, 1, 1, 0, 1],
    [1, 1, 0, 1, 0],
    [0, 1, 1, 1, 0],
    [1, 1, 1, 1, 0],
    [1, 1, 1, 1, 1],
    [0, 0, 0, 0, 0]]
 
printMaxSubSquare(M)
 
# This code is contributed by shinjanpatra
 
 
Output
Maximum size sub-matrix is:  1 1 1  1 1 1  1 1 1  

Time Complexity: O(m*n) where m is the number of rows and n is the number of columns in the given matrix.
Auxiliary space: O(n) where n is the number of columns in the given matrix.

Please refer complete article on Maximum size square sub-matrix with all 1s for more details!



Next Article
Python Program for Maximum and Minimum in a square matrix.
author
kartik
Improve
Article Tags :
  • Python Programs

Similar Reads

  • Python3 Program for Size of The Subarray With Maximum Sum
    An array is given, find length of the subarray having maximum sum. Examples : Input : a[] = {1, -2, 1, 1, -2, 1}Output : Length of the subarray is 2Explanation: Subarray with consecutive elements and maximum sum will be {1, 1}. So length is 2Input : ar[] = { -2, -3, 4, -1, -2, 1, 5, -3 }Output : Len
    4 min read
  • Python Program for Maximum and Minimum in a square matrix.
    Given a square matrix of order n*n, find the maximum and minimum from the matrix given. Examples: Input : arr[][] = {5, 4, 9, 2, 0, 6, 3, 1, 8}; Output : Maximum = 9, Minimum = 0 Input : arr[][] = {-5, 3, 2, 4}; Output : Maximum = 4, Minimum = -5 Naive Method : We find maximum and minimum of matrix
    3 min read
  • Python program to Sort Matrix by Maximum Row element
    Given a Matrix, sort rows by maximum element. Input : test_list = [[5, 7, 8], [9, 10, 3], [10, 18, 3], [0, 3, 5]] Output : [[10, 18, 3], [9, 10, 3], [5, 7, 8], [0, 3, 5]] Explanation : 18, 10, 8 and 5 are maximum elements in rows, hence sorted. Input : test_list = [[9, 10, 3], [10, 18, 3], [0, 3, 5]
    4 min read
  • Python - Sort Matrix by K Sized Subarray Maximum Sum
    Given Matrix, write a Python program to sort rows by maximum of K sized subarray sum. Examples: Input : test_list = [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [4, 3, 9, 3, 9], [5, 4, 3, 2, 1]], K = 3 Output : [[4, 3, 5, 2, 3], [6, 4, 2, 1, 1], [5, 4, 3, 2, 1], [4, 3, 9, 3, 9]] Explanation : 12 = 12 = 12
    4 min read
  • Python Program to Find maximum element of each row in a matrix
    Given a matrix, the task is to find the maximum element of each row.Examples:  Input : [1, 2, 3] [1, 4, 9] [76, 34, 21] Output : 3 9 76 Input : [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output : 21 65 56 Method 1: The idea is to run the loop for no_of_rows. Check each element inside the row and fi
    5 min read
  • Python - Row with Minimum Sum in Matrix
    We can have an application for finding the lists with the minimum value and print it. This seems quite an easy task and may also be easy to code, but having shorthands to perform the same are always helpful as this kind of problem can come in web development. Method #1 : Using reduce() + lambda The
    4 min read
  • Python Program for Maximum Product Subarray
    Given an array that contains both positive and negative integers, find the product of the maximum product subarray. Expected Time complexity is O(n) and only O(1) extra space can be used. Examples: Input: arr[] = {6, -3, -10, 0, 2}Output: 180 // The subarray is {6, -3, -10}Input: arr[] = {-1, -3, -1
    4 min read
  • Python program to search for the minimum element occurring consecutively n times in a matrix
    Given a matrix containing n rows. Each row has an equal number of m elements. The task is to find elements that come consecutively n times horizontally, vertically, diagonally in the matrix. If there are multiple such elements then print the smallest element. If there is no such element then print -
    4 min read
  • Python3 Program to Inplace rotate square matrix by 90 degrees | Set 1
    Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.Examples : Input:Matrix: 1 2 3 4 5 6 7 8 9Output: 3 6 9 2 5 8 1 4 7 The given matrix is rotated by 90 degree in anti-clockwise direction.Input: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output: 4 8 12
    4 min read
  • Python Program to Find the Maximum sum of i*arr[i] among all rotations of a given array
    Given an array arr[] of n integers, find the maximum that maximizes the sum of the value of i*arr[i] where i varies from 0 to n-1. Examples: Input: arr[] = {8, 3, 1, 2}Output: 29Explanation: Lets look at all the rotations,{8, 3, 1, 2} = 8*0 + 3*1 + 1*2 + 2*3 = 11{3, 1, 2, 8} = 3*0 + 1*1 + 2*2 + 8*3
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences