- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count all 0s which are blocked by 1s in binary matrix in C++
In this tutorial, we will be discussing a program to find the count of 0s which are blocked by 1s in a binary matrix.
For this we will be provided with a binary matrix. Our task is to find and count all the 0s in the matrix that are blocked by 1s.
Example
#include <iostream> using namespace std; #define Row 4 #define Col 5 int r[4] = { 0, 0, 1, -1 }; int c[4] = { 1, -1, 0, 0 }; bool isSafe(int x, int y, int M[][Col]) { if (x >= 0 && x <= Row && y >= 0 && y <= Col && M[x][y] == 0) return true; return false; } //performing DFS in the matrix void DFS(int x, int y, int M[][Col]) { //marking the node as visited M[x][y] = 1; for (int k = 0; k < 4; k++) if (isSafe(x + r[k], y + c[k], M)) DFS(x + r[k], y + c[k], M); } //returning count of blocked 0s int CountAllZero(int M[][Col]){ for (int i = 0; i < Col; i++) if (M[0][i] == 0) DFS(0, i, M); for (int i = 0; i < Col; i++) if (M[Row - 1][i] == 0) DFS(Row - 1, i, M); for (int i = 0; i < Row; i++) if (M[i][0] == 0) DFS(i, 0, M); for (int i = 0; i < Row; i++) if (M[i][Col - 1] == 0) DFS(i, Col - 1, M); //counting all zeros which are surrounded by 1 int result = 0; for (int i = 0; i < Row; i++) for (int j = 0; j < Col; j++) if (M[i][j] == 0) result++; return result; } int main(){ int M[][Col] = { { 1, 1, 1, 0, 1 },{ 1, 0, 0, 1, 0 },{ 1, 0, 1, 0, 1 },{ 0, 1, 1, 1, 1 } }; cout << CountAllZero(M) << endl; return 0; }
Output
4
- Related Articles
- XOR counts of 0s and 1s in binary representation in C++
- Count numbers have all 1s together in binary representation in C++
- Maximum size rectangle binary sub-matrix with all 1s in C++
- Maximum size rectangle binary sub-matrix with all 1s in C++ Program
- Count Substrings with equal number of 0s, 1s and 2s in C++
- Print n 0s and m 1s such that no two 0s and no three 1s are together in C Program
- Count all prefixes of the given binary array which are divisible by x in C++
- Program to count substrings with all 1s in binary string in Python
- Minimum flips to make all 1s in left and 0s in right in C++
- Segregate all 0s on right and 1s on left in JavaScript
- Count all the columns in a matrix which are sorted in descending in C++
- Find perimeter of shapes formed with 1s in binary matrix in C++
- Minimum toggles to partition a binary array so that it has first 0s then 1s in C++
- Largest subarray with equal number of 0s and 1s in C++
- Find row number of a binary matrix having maximum number of 1s in C++

Advertisements