Check if there are T number of Continuous of Blocks of 0s or not in given Binary Matrix


Introduction

Binary matrices are widely used in computer science and various fields to represent data or solve complex problems efficiently. In some cases, it becomes important to identify whether a given binary matrix contains continuous blocks of zeros. In this article, we will explore an elegant solution using C++ code that allows us to detect if there are T number of continuous blocks of zeroes within a given binary matrix. This approach is both intuitive and efficient, making it suitable for practical implementation.

Check if there are T number of continuous of blocks of 0s or not

Given a two-dimensional binary matrix with dimensions N x M and an integer T, we need to determine whether there exist T continuous blocks (where "continuous" means horizontally or vertically adjacent) of zeros in the matrix. To achieve this, let us break down the process step by step using both logic and algorithmic approaches.

Input Validation

Before diving into exploring patterns in the binary matrix, it's crucial to validate user inputs for appropriate dimensions and relevant characteristics. We must ensure that T falls within acceptable boundaries to provide feasible results while maintaining computational efficiency.

Traversing Through Rows and Columns

To ascertain continuous blocks of zeros efficiently, we must analyze both rows and columns separately. For instance, starting from row one (topmost), we will traverse through all elements column-wise until row N (bottommost). Simultaneously traversing through columns aids in capturing horizontal as well as vertical sequences naturally without missing any potential combinations.

Detecting Continuous Blocks

As we progress through each column in every row, identifying consecutive zeroes forms the cornerstone when detecting continuous zero blocks.

A binary matrix is an array comprised solely of 0s and 1s, where each element represents either an "off" or "on" state respectively. By analyzing these two states, we can discern distinctive patterns that may offer insights into interconnectedness or unique arrangements among adjacent elements.

Example

The binary matrix is taken as,

1 0 0 0 1
1 0 0 0 1
1 1 1 1 1
1 0 0 0 1

We need to find the number of continuous blocks of zeros in the matrix. The value of T is given as 3.

We can use Depth First Search (DFS) to find the continuous blocks of zeros in the matrix. We start by traversing the matrix row-wise and column-wise. If we encounter a zero element that has not been visited before, we push it onto a stack and start DFS from that element.

During DFS, we check the four adjacent cells of the current cell (top, bottom, left, right). If any of these cells are zero and have not been visited before, we push them onto the stack and continue DFS from that cell.

We also keep track of the number of continuous blocks of zeros we have encountered so far. If this count is greater than or equal to T, we return “Yes”. Otherwise, we continue DFS until all cells have been visited.

In this case, we start DFS from cell (0,1). We encounter two more zero elements at (0,2) and (0,3) and add them to our current path. We then backtrack to cell (0,1) and check its adjacent cells. We encounter another zero element at (1,1) and add it to our current path. We then backtrack to cell (0,1) again and check its adjacent cells. We do not encounter any more zero elements that have not been visited before.

We then start DFS from cell (3,1). We encounter two more zero elements at (3,2) and (3,3) and add them to our current path. We then backtrack to cell (3,1) and check its adjacent cells. We do not encounter any more zero elements that have not been visited before.

We have now found three continuous blocks of zeros in the matrix. Since this count is greater than or equal to T=3, the output is “Yes”.

Approach 1: C++ Code to check if there are T number of continuous of blocks of 0s or not

To accomplish our goal, we can utilize graph traversal techniques on the binary matrix while keeping track of visited cells. We will use depth-first search (DFS) algorithm combined with backtracking principles.

Algorithm

Step 1: Initialize necessary variables like define constants `N` and `M` representing the size of the input binary matrix, declare auxiliary boolean arrays 'visited' and 'inCurrentPath' each having size N x M, and set all elements in both arrays to false initially.

Step 2: Implement DFS function and include the main function

Step 3: Depending on the input binary matrix, the output is printed as either yes or no.

Example

#include<iostream>
#include<stack>
#include<bitset>

#define N 100
#define M 100

struct Node {
   int i;
   int j;
};

bool DFS(bool matrix[], int rows, int cols, int T)
{
   if(matrix == nullptr || rows <= 0 || cols <= 0 || T <= 0) // check for invalid input
      return false;

   std::bitset<N*M> visited; // declare bitset to mark visited cells
   std::bitset<N*M> inCurrentPath; // declare bitset to mark cells in current path
   std::stack<Node> s; // declare stack to store nodes for DFS

   for(int i=0;i<rows;++i){
      for(int j=0;j<cols;++j){

         if(matrix[i*cols+j] == 0 && !visited[i*cols+j]){

            s.push({i,j});
            int count = 0; // initialize count to zero for each new search

            while(!s.empty()){

               Node node = s.top();
               s.pop();

               if(node.i < 0 || node.i >= rows || node.j < 0 || node.j >= cols || visited[node.i*cols+node.j])
                  continue;

               visited[node.i*cols+node.j] = true;

               if(matrix[node.i*cols+node.j] == 0 && !inCurrentPath[node.i*cols+node.j]){
                  inCurrentPath[node.i*cols+node.j] = true;
                  count++;
               }

               if(count >= T){
                  std::cout << "Yes, the path is: "; // print yes and the path
                  for(int k=0;k<N*M;++k){
                     if(inCurrentPath[k]){
                        std::cout << "(" << k/cols << "," << k%cols << ") "; // print the coordinates of the cells in the path
                     }
                  }
                  std::cout << "\n";
                  return true;
               }

               s.push({node.i+1,node.j});
               s.push({node.i-1,node.j});
               s.push({node.i,node.j+1});
               s.push({node.i,node.j-1});
            }

            inCurrentPath.reset(); // reset the path after each search
         }
      }
   }

   std::cout << "No\n"; // print no if no path is found
   return false;
}

int main()
{
   bool matrix[N*M] = {1,1,0,0,1,
                  1,0,0,0,1,
                  1,1,1,1,1,
                  1,1,0,0,1,
                  }; // Binary matrix

   int T = 3; // Number of continuous blocks to find

   DFS(matrix, N, M, T); // call DFS function

   return 0;
}

Output

Yes, the path is: (0,2) (1,0) (1,1)

Conclusion

By utilizing the presented C++ code that employs graph traversal techniques involving depth-first search (DFS), we can conveniently determine the presence or absence of a given number (T) of continuous zero-blocks in a binary matrix. This solution offers an efficient approach to solving related problems associated with binary matrices and allows researchers and developers to create powerful algorithms efficiently.

Updated on: 09-Aug-2023

60 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements