Open In App

Check for Zero Sub-Matrix in 2D Grid

Last Updated : 09 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Given a 2D array Grid[][] of N rows and M columns along with two integers X and Y, then your task is to output YES, If there exists a sub-matrix of dimensions X and Y containing 0’s only else NO.

Examples:

Input: N = 3, M = 4, grid[][] = {{0, 0, 1, 1}, {0, 0, 1, 1}, {0, 0, 0, 0}}, X = 2, Y = 2
Output: YES
Explanation: The sub-matrix formed by first two rows and columns contains all 0s and has dimensions as 2*2. Thus, output is YES.

Input: N = 1, M = 1, grid[][] = {{1}}, X = 1, Y = 1
Output: NO
Explanation: It can be verified that there is no sub-matrix of size 1*1 in given matrix, which contains all 0s.

Approach: To solve the problem follow the below idea:

This can be solved by counting the number of 1’s at each point in a new grid. For each X and Y space we can iterate in a grid, If value comes out to be 0. Then grid of X*Y dimensions containing all 0’s exists. We can solve this problem in O(NxM) using Prefix Sum.

Below are the steps involved:

  • Create a new grid let say G[][] of size [N + 1][M + 1].
  • As the idea is to count the number of 1’s at each point, Therefore, follow the below formula:
    • G [i][j] = grid[i – 1][j – 1] + G[i – 1][j] + G[i][j – 1] – G[i – 1][j – 1].
  • For checking the possibility of the existence of a grid, We can again iterate in Prefix Sum Grid and check for 1’s in each X*Y submatrix:
    • Formula to check number of 1’s in the submatrix: G[i + X][j + Y] – G[i + X][j] – G[i][j + Y] + G[i][j].
  • If the value for above equation comes out to be 0
    • Return True
  • Else
    • Return False.

Below is the implementation of the above approach:

C++




// C++ Implementation of the given problem
#include <bits/stdc++.h>
#include <iostream>
using namespace std;
 
// Function to check whether a
// space exist or not
bool findSpace(vector<vector<int> > grid, int N, int M,
               int X, int Y)
{
 
    // Initializing a array of pref
    int G[N + 1][M + 1];
 
    // Iterating in grid
    for (int i = 1; i <= N; i++)
 
        for (int j = 1; j <= M; j++)
 
            G[i][j] = grid[i - 1][j - 1] + G[i - 1][j]
                      + G[i][j - 1] - G[i - 1][j - 1];
 
    // Iterate to check whether a grid of X and
    // Y dimension exist
    for (int i = 0; i + X <= N; i++)
 
        for (int j = 0; j + Y <= M; j++) {
            int ones = G[i + X][j + Y] - G[i + X][j]
                       - G[i][j + Y] + G[i][j];
 
            // If ones value is 0
            if (ones == 0)
 
                return true;
        }
 
    return false;
}
 
// Driver code
int main()
{
    // Inputs
    int N = 4;
    int M = 4;
    vector<vector<int> > grid = { { 0, 0, 1, 1 },
                                  { 0, 0, 1, 1 },
                                  { 0, 0, 0, 0 },
                                  { 0, 0, 0, 0 } };
    int X = 2;
    int Y = 4;
 
    // Function call
    bool result = findSpace(grid, N, M, X, Y);
 
    // Use boolalpha to print true/false
    cout << boolalpha << result;
    return 0;
}


Java




// Java program for the above approach
import java.util.Arrays;
 
public class GFG {
 
    // Function to check whether a space exists or not
    static boolean findSpace(int[][] grid, int N, int M,
                             int X, int Y)
    {
 
        // Initializing a 2D array of prefix sums
        int[][] G = new int[N + 1][M + 1];
 
        // Iterating in the grid
        for (int i = 1; i <= N; i++)
            for (int j = 1; j <= M; j++)
                G[i][j] = grid[i - 1][j - 1] + G[i - 1][j]
                          + G[i][j - 1] - G[i - 1][j - 1];
 
        // Iterate to check whether a grid of X and Y
        // dimension exists
        for (int i = 0; i + X <= N; i++)
            for (int j = 0; j + Y <= M; j++) {
                int ones = G[i + X][j + Y] - G[i + X][j]
                           - G[i][j + Y] + G[i][j];
 
                // If ones value is 0
                if (ones == 0)
                    return true;
            }
 
        return false;
    }
 
    // Driver code
    public static void main(String[] args)
    {
        // Inputs
        int N = 4;
        int M = 4;
        int[][] grid = { { 0, 0, 1, 1 },
                         { 0, 0, 1, 1 },
                         { 0, 0, 0, 0 },
                         { 0, 0, 0, 0 } };
        int X = 2;
        int Y = 4;
 
        // Function call
        boolean result = findSpace(grid, N, M, X, Y);
 
        // Print the result
        System.out.println(result);
    }
}
 
// This code is contributed by Susobhan Akhuli


Python3




def find_space(grid, N, M, X, Y):
    # Initializing a 2D prefix sum array
    G = [[0] * (M + 1) for _ in range(N + 1)]
 
    # Iterating in the grid to compute prefix sums
    for i in range(1, N + 1):
        for j in range(1, M + 1):
            G[i][j] = grid[i - 1][j - 1] + G[i - 1][j] + G[i][j - 1] - G[i - 1][j - 1]
 
    # Iterate to check whether a grid of X and Y dimension exists
    for i in range(N - X + 1):
        for j in range(M - Y + 1):
            ones = G[i + X][j + Y] - G[i + X][j] - G[i][j + Y] + G[i][j]
 
            # If ones value is 0
            if ones == 0:
                return True
 
    return False
 
# Driver code
if __name__ == "__main__":
    # Inputs
    N = 4
    M = 4
    grid = [[0, 0, 1, 1],
            [0, 0, 1, 1],
            [0, 0, 0, 0],
            [0, 0, 0, 0]]
    X = 2
    Y = 4
 
    # Function call
    result = find_space(grid, N, M, X, Y)
 
    # Print the result using boolalpha to represent true/false
    print(result)
 
# This code is contributed by shivamgupta0987654321


C#




// C# program for the above approach
using System;
 
public class GFG {
    // Function to check whether a space exists or not
    static bool FindSpace(int[, ] grid, int N, int M, int X,
                          int Y)
    {
        // Initializing an array of pref
        int[, ] G = new int[N + 1, M + 1];
 
        // Iterating in grid
        for (int i = 1; i <= N; i++) {
            for (int j = 1; j <= M; j++) {
                G[i, j] = grid[i - 1, j - 1] + G[i - 1, j]
                          + G[i, j - 1] - G[i - 1, j - 1];
            }
        }
 
        // Iterate to check whether a grid of X and Y
        // dimension exists
        for (int i = 0; i + X <= N; i++) {
            for (int j = 0; j + Y <= M; j++) {
                int ones = G[i + X, j + Y] - G[i + X, j]
                           - G[i, j + Y] + G[i, j];
 
                // If ones value is 0
                if (ones == 0) {
                    return true;
                }
            }
        }
 
        return false;
    }
 
    // Driver code
    static void Main()
    {
        // Inputs
        int N = 4;
        int M = 4;
        int[, ] grid = { { 0, 0, 1, 1 },
                         { 0, 0, 1, 1 },
                         { 0, 0, 0, 0 },
                         { 0, 0, 0, 0 } };
        int X = 2;
        int Y = 4;
 
        // Function call
        bool result = FindSpace(grid, N, M, X, Y);
 
        // Print the result
        Console.WriteLine(result);
    }
}
 
// This code is contributed by Susobhan Akhuli


Javascript




// JavaScript Implementation of the given problem
 
// Function to check whether a space exists or not
function findSpace(grid, N, M, X, Y) {
    // Initializing a 2D prefix sum array
    let G = new Array(N + 1).fill(null).map(() => new Array(M + 1).fill(0));
 
    // Calculating prefix sum
    for (let i = 1; i <= N; i++) {
        for (let j = 1; j <= M; j++) {
            G[i][j] = grid[i - 1][j - 1] + G[i - 1][j] + G[i][j - 1] - G[i - 1][j - 1];
        }
    }
 
    // Iterate to check whether a grid of
    // X and Y dimension exists
    for (let i = 0; i + X <= N; i++) {
        for (let j = 0; j + Y <= M; j++) {
            let ones = G[i + X][j + Y] - G[i + X][j] - G[i][j + Y] + G[i][j];
             
            // If ones value is 0
            if (ones === 0) {
                return true;
            }
        }
    }
    return false;
}
 
// Driver code
 
// Inputs
let N = 4;
let M = 4;
let grid = [
    [0, 0, 1, 1],
    [0, 0, 1, 1],
    [0, 0, 0, 0],
    [0, 0, 0, 0]
];
let X = 2;
let Y = 4;
 
// Function call
let result = findSpace(grid, N, M, X, Y);
 
// Print true/false
console.log(result);


Output

true






Time Complexity: O(N * M), As two nested loops are there.
Auxiliary Space: O(N * M), As an extra 2D matrix G[][] of dimensions N+1 and M+1 is used.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads