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
  • DSA
  • Interview Problems on DP
  • Practice DP
  • MCQs on DP
  • Tutorial on Dynamic Programming
  • Optimal Substructure
  • Overlapping Subproblem
  • Memoization
  • Tabulation
  • Tabulation vs Memoization
  • 0/1 Knapsack
  • Unbounded Knapsack
  • Subset Sum
  • LCS
  • LIS
  • Coin Change
  • Word Break
  • Egg Dropping Puzzle
  • Matrix Chain Multiplication
  • Palindrome Partitioning
  • DP on Arrays
  • DP with Bitmasking
  • Digit DP
  • DP on Trees
  • DP on Graph
Open In App
Next Article:
Find Matrix With Given Row and Column Sums
Next article icon

Largest square sub-matrix with equal row, column, and diagonal sum

Last Updated : 16 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a matrix mat[][] of dimensions N*M, the task is to find the size of the largest square submatrix such that the sum of all rows, columns, diagonals in that submatrix are equal.

Examples:

Input: N = 3, M = 4, mat[][] = [[5, 1, 3, 1], [9, 3, 3, 1], [1, 3, 3, 8]]
Output: 2
Explanation:
The submatrix which satisfies all the given conditions is shown in bold
5 1 3 1
9 3 3 1
1 3 3 8
Therefore, the size of the submatrix is 2.

Input: N = 4, M = 5, mat[][] = [[7, 1, 4, 5, 6], [2, 5, 1, 6, 4], [1, 5, 4, 3, 2], [1, 2, 7, 3, 4]]
Output: 3
Explanation:
The submatrix which satisfies all the given conditions is shown in bold
7 1 4 5 6
2 5 1 6 4
1 5 4 3 2
1 2 7 3 4
Therefore, the size of the submatrix is 3.

Approach:

The given problem can be solved by finding the Prefix Sum of all the rows and the columns and then iterate for all possible sizes of the square submatrix from each cell of the matrix and if there exists any such square matrix that satisfies the given criteria then print that size of a square matrix. Follow the below steps to solve the problem:

  • Maintain two prefix sum arrays prefixSumRow[] and prefixSumColumn[] and store the prefix sum of rows and columns of the given matrix respectively.
  • Perform the following steps to check if any square matrix starting from the cell (i, j) of size K satisfy the given criteria or not:
    1. Find the sum of elements of primary diagonal of the submatrix mat[i][j] to mat[i + K][j + K] and store it in the variable, say sum.
    2. If the value of the sum is the same as the value mentioned below then return true. Otherwise, return false.
      • The prefix sum of all the rows i.e., the value of prefixSumRow[k][j + K] - prefixSumRow[k][j] for all values of k over then range [i, i + K].
      • The prefix sum of all the columns i.e., the value of prefixSumColumn[i + K][j] - prefixSumColumn[i][k] for all values of k over then range [j, j + K].
      • The prefix sum of anti-diagonal elements.
  • Now, iterate for all possible sizes of the square matrix that can be formed over the range [min(N, M), 1] and if there exist any possible satisfies the given criteria using the steps in the above steps, then print that size of a square matrix.

Below is the implementation of the above approach:

C++
// C++ program for the above approach #include <bits/stdc++.h> using namespace std;  // Define the prefix sum arrays globally int prefix_sum_row[50][51]; int prefix_sum_col[51][50];  bool is_valid(int r, int c, int size, vector<vector<int> >& grid){     int r_end = r + size, c_end = c + size;      // Diagonal sum     int sum = 0;     for (int i = r, j = c; i < r_end; i++, j++) {         sum += grid[i][j];     }      // Check each row     for (int i = r; i < r_end; i++) {         if (prefix_sum_row[i][c_end] - prefix_sum_row[i][c] != sum) {             return false;         }     }      // Check each column     for (int i = c; i < c_end; i++) {         if (prefix_sum_col[r_end][i] - prefix_sum_col[r][i] != sum) {             return false;         }     }      // Check anti-diagonal     int ad_sum = 0;     for (int i = r, j = c_end - 1; i < r_end; i++, j--) {         ad_sum += grid[i][j];     }      return ad_sum == sum; }  int largestSquareValidMatrix(vector<vector<int> >& grid){     // Store the size of the given grid     int m = grid.size(), n = grid[0].size();      // Compute the prefix sum for the rows     for (int i = 0; i < m; i++) {         for (int j = 1; j <= n; j++) {             prefix_sum_row[i][j] = prefix_sum_row[i][j - 1] + grid[i][j - 1];         }     }      // Compute the prefix sum for the columns     for (int i = 1; i <= m; i++) {         for (int j = 0; j < n; j++) {             prefix_sum_col[i][j] = prefix_sum_col[i - 1][j] + grid[i - 1][j];         }     }      // Check for all possible square submatrix     for (int size = min(m, n); size > 1; size--) {         for (int i = 0; i <= m - size; i++) {             for (int j = 0; j <= n - size; j++) {                 if (is_valid(i, j, size, grid)) {                     return size;                 }             }         }     }      return 1; }  // Driver Code int main(){     vector<vector<int> > grid = { { 7, 1, 4, 5, 6 },                                   { 2, 5, 1, 6, 4 },                                   { 1, 5, 4, 3, 2 },                                   { 1, 2, 7, 3, 4 } };     cout << largestSquareValidMatrix(grid);     return 0; } 
Java
// Java program for the above approach class GFG {     // Define the prefix sum arrays globally     public static int[][] prefix_sum_row = new int[50][51];     public static int[][] prefix_sum_col = new int[51][50];      public static boolean is_valid(int r, int c, int size, int[][] grid) {         int r_end = r + size, c_end = c + size;          // Diagonal sum         int sum = 0;         for (int i = r, j = c; i < r_end; i++, j++) {             sum += grid[i][j];         }          // Check each row         for (int i = r; i < r_end; i++) {             if (prefix_sum_row[i][c_end] - prefix_sum_row[i][c] != sum) {                 return false;             }         }          // Check each column         for (int i = c; i < c_end; i++) {             if (prefix_sum_col[r_end][i] - prefix_sum_col[r][i] != sum) {                 return false;             }         }          // Check anti-diagonal         int ad_sum = 0;         for (int i = r, j = c_end - 1; i < r_end; i++, j--) {             ad_sum += grid[i][j];         }          return ad_sum == sum;     }      public static int largestSquareValidMatrix(int[][] grid) {         // Store the size of the given grid         int m = grid.length, n = grid[0].length;          // Compute the prefix sum for the rows         for (int i = 0; i < m; i++) {             for (int j = 1; j <= n; j++) {                 prefix_sum_row[i][j] = prefix_sum_row[i][j - 1] + grid[i][j - 1];             }         }          // Compute the prefix sum for the columns         for (int i = 1; i <= m; i++) {             for (int j = 0; j < n; j++) {                 prefix_sum_col[i][j] = prefix_sum_col[i - 1][j] + grid[i - 1][j];             }         }          // Check for all possible square submatrix         for (int size = Math.min(m, n); size > 1; size--) {             for (int i = 0; i <= m - size; i++) {                 for (int j = 0; j <= n - size; j++) {                     if (is_valid(i, j, size, grid)) {                         return size;                     }                 }             }         }          return 1;     }      // Driver Code     public static void main(String args[]) {         int[][] grid = { { 7, 1, 4, 5, 6 }, { 2, 5, 1, 6, 4 }, { 1, 5, 4, 3, 2 }, { 1, 2, 7, 3, 4 } };         System.out.println(largestSquareValidMatrix(grid));      }  }  // This code is contributed by saurabh_jaiswal. 
Python
## Python program for the above approach:  ## Define the prefix sum arrays globally prefix_sum_row = [[0]*51 for _ in range(50)] prefix_sum_col = [[0]*50 for _ in range(51)]  def is_valid(r, c, size, grid):          r_end = r + size     c_end = c + size      ## Diagonal sum     sum = 0;     j = c     for i in range(r, r_end):         sum += grid[i][j];         j+=1      ## Check each row     for i in range(r, r_end):         if ((prefix_sum_row[i][c_end] - prefix_sum_row[i][c]) != sum):             return False      ## Check each column     for i in range(c, c_end):         if ((prefix_sum_col[r_end][i] - prefix_sum_col[r][i]) != sum):             return False      ## Check anti-diagonal     ad_sum = 0;     j = c_end - 1     for i in range(r, r_end):         ad_sum += grid[i][j]         j-=1      return (ad_sum == sum)  def largestSquareValidMatrix(grid):      ## Store the size of the given grid     m = len(grid)     n = len(grid[0])      ## Compute the prefix sum for the rows     for i in range(0, m):         for j in range(1, n+1):             prefix_sum_row[i][j] = prefix_sum_row[i][j - 1] + grid[i][j - 1];          ## Compute the prefix sum for the columns     for i in range(1, m+1):         for j in range(0, n):             prefix_sum_col[i][j] = prefix_sum_col[i - 1][j] + grid[i - 1][j]       ## Check for all possible square submatrix     for size in range(min(m, n), 1, -1):         for i in range(0, m-size+1):             for j in range(0, n-size+1):                 if (is_valid(i, j, size, grid)):                     return size      return 1  ## Driver code if __name__=='__main__':      grid =  [   [ 7, 1, 4, 5, 6 ],                 [ 2, 5, 1, 6, 4 ],                 [ 1, 5, 4, 3, 2 ],                 [ 1, 2, 7, 3, 4 ]             ]                  print(largestSquareValidMatrix(grid))      # This code is contributed by subhamgoyal2014. 
C#
// C# program for the above approach using System; class GFG {        // Define the prefix sum arrays globally     public static int[,] prefix_sum_row = new int[50,51];     public static int[,] prefix_sum_col = new int[51,50];      public static bool is_valid(int r, int c, int size, int[,] grid) {         int r_end = r + size, c_end = c + size;          // Diagonal sum         int sum = 0;         for (int i = r, j = c; i < r_end; i++, j++) {             sum += grid[i,j];         }          // Check each row         for (int i = r; i < r_end; i++) {             if (prefix_sum_row[i,c_end] - prefix_sum_row[i,c] != sum) {                 return false;             }         }          // Check each column         for (int i = c; i < c_end; i++) {             if (prefix_sum_col[r_end,i] - prefix_sum_col[r,i] != sum) {                 return false;             }         }          // Check anti-diagonal         int ad_sum = 0;         for (int i = r, j = c_end - 1; i < r_end; i++, j--) {             ad_sum += grid[i,j];         }          return ad_sum == sum;     }      public static int largestSquareValidMatrix(int[,] grid) {         // Store the size of the given grid         int m = grid.GetLength(0), n = grid.GetLength(1);          // Compute the prefix sum for the rows         for (int i = 0; i < m; i++) {             for (int j = 1; j <= n; j++) {                 prefix_sum_row[i,j] = prefix_sum_row[i,j - 1] + grid[i,j - 1];             }         }          // Compute the prefix sum for the columns         for (int i = 1; i <= m; i++) {             for (int j = 0; j < n; j++) {                 prefix_sum_col[i,j] = prefix_sum_col[i - 1,j] + grid[i - 1,j];             }         }          // Check for all possible square submatrix         for (int size = Math.Min(m, n); size > 1; size--) {             for (int i = 0; i <= m - size; i++) {                 for (int j = 0; j <= n - size; j++) {                     if (is_valid(i, j, size, grid)) {                         return size;                     }                 }             }         }          return 1;     }      // Driver Code     public static void Main() {         int[,] grid = { { 7, 1, 4, 5, 6 }, { 2, 5, 1, 6, 4 },                        { 1, 5, 4, 3, 2 }, { 1, 2, 7, 3, 4 } };         Console.WriteLine(largestSquareValidMatrix(grid));      }  }  // This code is contributed by ukasp. 
JavaScript
// JavaScript Program to implement // the above approach  // Define the prefix sum arrays globally let prefix_sum_row = new Array(50); for (let i = 0; i < prefix_sum_row.length; i++) {     prefix_sum_row[i] = new Array(51).fill(0); } let prefix_sum_col = new Array(50); for (let i = 0; i < prefix_sum_col.length; i++) {     prefix_sum_col[i] = new Array(51).fill(0); } function is_valid(r, c, size, grid) {     let r_end = r + size, c_end = c + size;      // Diagonal sum     let sum = 0;     for (let i = r, j = c; i < r_end; i++, j++) {         sum += grid[i][j];     }     // Check each row     for (let i = r; i < r_end; i++) {         if (prefix_sum_row[i][c_end]             - prefix_sum_row[i][c]             != sum) {             return false;         }     }      // Check each column     for (let i = c; i < c_end; i++) {         if (prefix_sum_col[r_end][i]             - prefix_sum_col[r][i]             != sum) {             return false;         }     }      // Check anti-diagonal     let ad_sum = 0;     for (let i = r, j = c_end - 1; i < r_end;         i++, j--) {         ad_sum += grid[i][j];     }      return ad_sum == sum; }  function largestSquareValidMatrix(grid) {     // Store the size of the given grid     let m = grid.length, n = grid[0].length;      // Compute the prefix sum for the rows     for (let i = 0; i < m; i++) {         for (let j = 1; j <= n; j++) {             prefix_sum_row[i][j]                 = prefix_sum_row[i][j - 1]                 + grid[i][j - 1];         }     }      // Compute the prefix sum for the columns     for (let i = 1; i <= m; i++) {         for (let j = 0; j < n; j++) {             prefix_sum_col[i][j]                 = prefix_sum_col[i - 1][j]                 + grid[i - 1][j];         }     }      // Check for all possible square submatrix     for (let size = Math.min(m, n); size > 1; size--) {         for (let i = 0; i <= m - size; i++) {             for (let j = 0; j <= n - size; j++) {                 if (is_valid(i, j, size, grid)) {                     return size;                 }             }         }     }      return 1; }  // Driver Code  let grid = [[7, 1, 4, 5, 6], [2, 5, 1, 6, 4], [1, 5, 4, 3, 2], [1, 2, 7, 3, 4]]; console.log(largestSquareValidMatrix(grid));  // This code is contributed by Potta Lokesh 

Output
3

Time Complexity: O(N*M*min(N, M)2), where N is the number of
Auxiliary Space: O(N*M)


Next Article
Find Matrix With Given Row and Column Sums

K

kartikmodi
Improve
Article Tags :
  • Dynamic Programming
  • Greedy
  • Mathematical
  • Matrix
  • DSA
  • prefix-sum
  • submatrix
Practice Tags :
  • Dynamic Programming
  • Greedy
  • Mathematical
  • Matrix
  • prefix-sum

Similar Reads

  • Largest row-wise and column-wise sorted sub-matrix
    Given an N * M matrix mat[][], the task is to find the area-wise largest rectangular sub-matrix such that each column and each row of the sub-matrix is strictly increasing. Examples: Input: mat[][] = {{1, 2, 3}, {4, 5, 6}, {1, 2, 3}} Output: 6 Largest sub-matrix will be {{1, 2, 3}, {4, 5, 6}}. Numbe
    13 min read
  • Find Matrix With Given Row and Column Sums
    Given two arrays rowSum[] and colSum[] of size n and m respectively, the task is to construct a matrix of dimensions n × m such that the sum of matrix elements in every ith row is rowSum[i] and the sum of matrix elements in every jth column is colSum[j]. Note: The resultant matrix can have only non-
    15 min read
  • Count rows/columns with sum equals to diagonal sum
    Given an n x n square matrix, count all rows and columns whose sum is equal to the sum of any principal diagonal or secondary diagonal. Examples: Input : n = 3 arr[][] = { {1, 2, 3}, {4, 5, 2}, {7, 9, 10}}; Output : 2 In first example sum of principal diagonal = (1 + 5 + 10) = 16 and sum of secondar
    8 min read
  • Largest area rectangular sub-matrix with equal number of 1's and 0's
    Given a binary matrix. The problem is to find the largest area rectangular sub-matrix with equal number of 1's and 0's. Examples: Input : mat[][] = { {0, 0, 1, 1}, {0, 1, 1, 0}, {1, 1, 1, 0}, {1, 0, 0, 1} } Output : 8 sq. units (Top, left): (0, 0) (Bottom, right): (3, 1) Input : mat[][] = { {0, 0, 1
    15+ min read
  • Construct a square matrix such that the sum of each row and column is odd
    Given an integer N. Then your task is to output a square matrix of length N using the numbers from the range [1, N2] such that the sum of each row and column is odd. Note: If there are multiple solution, then print any of them. Examples: Input: N = 2 Output: {{1, 2}, {4, 3}} Explanation: Let us calc
    12 min read
  • Largest sub-matrix with all equal elements
    Given a binary matrix of size N * M, the task is to find the largest area sub-matrix such that all elements in it are same i.e. either all are 0 or all are 1. Print the largest possible area of such matrix. Examples: Input: mat[][] = { {1, 1, 0, 1, 0, 0, 0, 0}, {0, 1, 1, 1, 1, 0, 0, 1}, {1, 0, 0, 1,
    15+ min read
  • Find row and column pair in given Matrix with equal row and column sum
    Given a matrix Mat of size N x M, the task is to find all the pairs of rows and columns where the sum of elements in the row is equal to the sum of elements in the columns. Examples: Input: M = {{1, 2, 2}, {1, 5, 6}, {3, 8, 9}}Output: {{1, 1}}Explanation: The sum of elements of rows and columns of m
    8 min read
  • Print all the sub diagonal elements of the given square matrix
    Given a square matrix mat[][] of size n * n. The task is to print all the elements which lie on the sub-diagonal of the given matrix.Examples: Input: mat[][] = { {1, 2, 3}, {3, 3, 4, }, {2, 4, 6}} Output: 3 4Input: mat[][] = { {1, 2, 3, 4}, {3, 3, 4, 4}, {2, 4, 6, 3}, {1, 1, 1, 3}} Output: 3 4 1 Rec
    7 min read
  • Count all square sub-matrix with sum greater than the given number S
    Given a matrix mat[][] and two integers K and S, the task is to count all K x K sub-matrix such that the sum of all the elements in the sub-matrix is greater than or equal to S. Examples: Input: K = 2, S = 15 mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output: 3 Explanation: In the given matrix ther
    15 min read
  • Construct a matrix with sum equal to the sum of diagonal elements
    Given an integer N, the task is to construct a matrix of size N2 using positive and negative integers and excluding 0, such that the sum of the matrix is equal to the sum of the diagonal of the matrix. Examples: Input: N = 2 Output: 1 -2 2 4 Explanation: Diagonal sum = (1 + 4) = 5 Matrix sum = (1 -
    4 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