Open In App

Counting 1’s Surrounded by Even 0’s

Last Updated : 30 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an ‘n x m’ matrix composed solely of ‘0’s and ‘1’s, the task is to determine the count of ‘1’s that are enclosed by an even number (greater than zero) of neighboring ‘0’s. The surroundings of a matrix cell encompass the eight neighboring cells, including those diagonally adjacent.

Examples:

Input: matrix = {{1, 0, 0}, {1, 1, 0}, {0, 1, 0}}
Output: 1
Explanation: 1 that occurs in the 1st row and 1st column, has 3 surrounding elements 0,1 and 1. The occurrence of zero is odd. 1 that occurs in the 2nd row and 1st column has 5 surrounding elements 1,0,1,1 and 0. The occurrence of zero is even. 1 that occurs in the 2nd row and the 2nd column has 8 surrounding elements. The occurrence of 0 is odd. Similarly, for the 1 that occurs in the 3rd row and 2nd column, the occurrence of zero in its 5 surrounding elements is odd. Hence, the output is 1.

Input: matrix = {{1}}
Output: 0
Explanation: There is only 1 element in the matrix. Hence, it has no surroundings, so its count for even 0’s is 0 for the whole matrix. 0 is even but we want the occurrence of a zero in the surrounding at least once. Hence, the output is 0.

Approach: To solve the problem follow the below steps:

  • For each cell in the matrix:
    a. If the cell contains a 1, proceed to analyze its surroundings.
    b. Create a counter variable `zeroCount` to keep track of the number of surrounding 0’s.
  • For each of the eight surrounding cells (above, below, left, right, diagonals):
    a. Check if the surrounding cell exists within the matrix boundaries.
    b. If the surrounding cell’s value is 0, increment the `zeroCount`.
  • After analyzing the surroundings, check two conditions:
    a. If `zeroCount` is even.
    b. If `zeroCount` is greater than 0.
  • If both conditions are satisfied, increment the `result` counter.
  • Finally, return the `result` count, which represents the number of 1’s that meet the specified condition.

Below is the implementation of above approach:

C++




// C++ code for the above approach:
#include <bits/stdc++.h>
using namespace std;
 
class Solution {
public:
    int Count(vector<vector<int> >& matrix)
    {
        int numRows = matrix.size();
        int numCols = matrix[0].size();
        int result = 0;
 
        // Iterate through each cell in the matrix
        for (int row = 0; row < numRows; ++row) {
            for (int col = 0; col < numCols; ++col) {
 
                // Check if the current cell is
                // 1 Count of adjacent cells
                // containing 0
                if (matrix[row][col]) {
 
                    int zeroCount = 0;
 
                    // Check the surrounding 8
                    // cells for zeroes
 
                    // Check top cell
                    if (row - 1 >= 0)
                        zeroCount
                            += matrix[row - 1][col] == 0;
 
                    // Check bottom cell
                    if (row + 1 < numRows)
                        zeroCount
                            += matrix[row + 1][col] == 0;
 
                    // Check left cell
                    if (col - 1 >= 0)
                        zeroCount
                            += matrix[row][col - 1] == 0;
 
                    // Check right cell
                    if (col + 1 < numCols)
                        zeroCount
                            += matrix[row][col + 1] == 0;
 
                    // Check top-left cell
                    if (row - 1 >= 0 && col - 1 >= 0)
                        zeroCount
                            += matrix[row - 1][col - 1]
                               == 0;
 
                    // Check top-right cell
                    if (row - 1 >= 0 && col + 1 < numCols)
                        zeroCount
                            += matrix[row - 1][col + 1]
                               == 0;
 
                    // Check bottom-left
                    // cell
                    if (row + 1 < numRows && col - 1 >= 0)
                        zeroCount
                            += matrix[row + 1][col - 1]
                               == 0;
 
                    // Check bottom-right
                    // cell
                    if (row + 1 < numRows
                        && col + 1 < numCols)
                        zeroCount
                            += matrix[row + 1][col + 1]
                               == 0;
 
                    // If adjacent zeros
                    // are even and
                    // nonzero
                    if (!(zeroCount & 1) && zeroCount)
 
                        // Increment the result
                        // count
                        result++;
                }
            }
        }
 
        // Return the final count of desired
        // cells
        return result;
    }
};
 
// Drivers code
int main()
{
 
    int n = 3, m = 3;
    vector<vector<int> > matrix
        = { { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } };
 
    Solution ob;
 
    // Calculate the result using
    // the Solution class
    int ans = ob.Count(matrix);
 
    // Output the result
    cout << ans << "\n";
 
    return 0;
}


Java




import java.util.*;
 
class Solution {
    public int count(int[][] matrix)
    {
        int numRows = matrix.length;
        int numCols = matrix[0].length;
        int result = 0;
 
        // Iterate through each cell in the matrix
        for (int row = 0; row < numRows; ++row) {
            for (int col = 0; col < numCols; ++col) {
                if (matrix[row][col]
                    == 1) { // Check if the current cell is
                            // 1
                    int zeroCount = 0; // Count of adjacent
                                       // cells containing 0
 
                    // Check the surrounding 8 cells for
                    // zeros
                    if (row - 1 >= 0)
                        zeroCount
                            += matrix[row - 1][col] == 0
                                   ? 1
                                   : 0; // Check top cell
                    if (row + 1 < numRows)
                        zeroCount
                            += matrix[row + 1][col] == 0
                                   ? 1
                                   : 0; // Check bottom cell
                    if (col - 1 >= 0)
                        zeroCount
                            += matrix[row][col - 1] == 0
                                   ? 1
                                   : 0; // Check left cell
                    if (col + 1 < numCols)
                        zeroCount
                            += matrix[row][col + 1] == 0
                                   ? 1
                                   : 0; // Check right cell
                    if (row - 1 >= 0 && col - 1 >= 0)
                        zeroCount
                            += matrix[row - 1][col - 1] == 0
                                   ? 1
                                   : 0; // Check top-left
                                        // cell
                    if (row - 1 >= 0 && col + 1 < numCols)
                        zeroCount
                            += matrix[row - 1][col + 1] == 0
                                   ? 1
                                   : 0; // Check top-right
                                        // cell
                    if (row + 1 < numRows && col - 1 >= 0)
                        zeroCount
                            += matrix[row + 1][col - 1] == 0
                                   ? 1
                                   : 0; // Check bottom-left
                                        // cell
                    if (row + 1 < numRows
                        && col + 1 < numCols)
                        zeroCount
                            += matrix[row + 1][col + 1] == 0
                                   ? 1
                                   : 0; // Check
                                        // bottom-right cell
 
                    if ((zeroCount % 2 == 0)
                        && zeroCount
                               > 0) // If adjacent zeros are
                                    // even and nonzero
                        result++; // Increment the result
                                  // count
                }
            }
        }
 
        return result; // Return the final count of desired
                       // cells
    }
}
 
public class Main {
    public static void main(String[] args)
    {
        int tc = 1;
        while (tc-- > 0) {
            int n = 3, m = 3;
            int[][] matrix
                = { { 1, 0, 0 }, { 1, 1, 0 }, { 0, 1, 0 } };
 
            Solution ob = new Solution();
            int ans = ob.count(
                matrix); // Calculate the result using the
                         // Solution class
            System.out.println(ans); // Output the result
        }
    }
}


Python




class Solution:
    def count(self, matrix):
        numRows = len(matrix)
        numCols = len(matrix[0])
        result = 0
 
        # Iterate through each cell in the matrix
        for row in range(numRows):
            for col in range(numCols):
                if matrix[row][col]:  # Check if the current cell is 1
                    zeroCount = 0  # Count of adjacent cells containing 0
 
                    # Check the surrounding 8 cells for zeros
                    if row - 1 >= 0:
                        # Check top cell
                        zeroCount += matrix[row - 1][col] == 0
                    if row + 1 < numRows:
                        # Check bottom cell
                        zeroCount += matrix[row + 1][col] == 0
                    if col - 1 >= 0:
                        # Check left cell
                        zeroCount += matrix[row][col - 1] == 0
                    if col + 1 < numCols:
                        # Check right cell
                        zeroCount += matrix[row][col + 1] == 0
                    if row - 1 >= 0 and col - 1 >= 0:
                        # Check top-left cell
                        zeroCount += matrix[row - 1][col - 1] == 0
                    if row - 1 >= 0 and col + 1 < numCols:
                        # Check top-right cell
                        zeroCount += matrix[row - 1][col + 1] == 0
                    if row + 1 < numRows and col - 1 >= 0:
                        # Check bottom-left cell
                        zeroCount += matrix[row + 1][col - 1] == 0
                    if row + 1 < numRows and col + 1 < numCols:
                        # Check bottom-right cell
                        zeroCount += matrix[row + 1][col + 1] == 0
 
                    if zeroCount % 2 == 0 and zeroCount != 0# If adjacent zeros are even and nonzero
                        result += 1  # Increment the result count
 
        return result  # Return the final count of desired cells
 
 
if __name__ == "__main__":
    tc = 1
    while tc > 0:
        n, m = 3, 3
        matrix = [[1, 0, 0], [1, 1, 0], [0, 1, 0]]
 
        ob = Solution()
        ans = ob.count(matrix)  # Calculate the result using the Solution class
        print(ans)  # Output the result
        tc -= 1


C#




using System;
 
class Solution
{
    public int Count(int[][] matrix)
    {
        int numRows = matrix.Length;
        int numCols = matrix[0].Length;
        int result = 0;
 
        // Iterate through each cell in the matrix
        for (int row = 0; row < numRows; ++row)
        {
            for (int col = 0; col < numCols; ++col)
            {
                if (matrix[row][col] == 1) // Check if the current cell is 1
                {
                    int zeroCount = 0; // Count of adjacent cells containing 0
 
                    // Check the surrounding 8 cells for zeros
                    if (row - 1 >= 0)
                        zeroCount += matrix[row - 1][col] == 0 ? 1 : 0; // Check top cell
                    if (row + 1 < numRows)
                        zeroCount += matrix[row + 1][col] == 0 ? 1 : 0; // Check bottom cell
                    if (col - 1 >= 0)
                        zeroCount += matrix[row][col - 1] == 0 ? 1 : 0; // Check left cell
                    if (col + 1 < numCols)
                        zeroCount += matrix[row][col + 1] == 0 ? 1 : 0; // Check right cell
                    if (row - 1 >= 0 && col - 1 >= 0)
                        zeroCount += matrix[row - 1][col - 1] == 0 ? 1 : 0; // Check top-left cell
                    if (row - 1 >= 0 && col + 1 < numCols)
                        zeroCount += matrix[row - 1][col + 1] == 0 ? 1 : 0; // Check top-right cell
                    if (row + 1 < numRows && col - 1 >= 0)
                        zeroCount += matrix[row + 1][col - 1] == 0 ? 1 : 0; // Check bottom-left cell
                    if (row + 1 < numRows && col + 1 < numCols)
                        zeroCount += matrix[row + 1][col + 1] == 0 ? 1 : 0; // Check bottom-right
                                                                            // cell
 
                    if (zeroCount % 2 == 0 && zeroCount > 0) // If adjacent zeros are even
                                                             // and nonzero
                        result++; // Increment the result count
                }
            }
        }
 
        return result; // Return the final count of desired cells
    }
}
 
class MainClass
{
    public static void Main(string[] args)
    {
        int tc = 1;
        while (tc-- > 0)
        {
            int[][] matrix = { new[] { 1, 0, 0 }, new[] { 1, 1, 0 }, new[] { 0, 1, 0 } };
 
            Solution ob = new Solution();
            int ans = ob.Count(matrix); // Calculate the result using the Solution class
            Console.WriteLine(ans); // Output the result
        }
    }
}


Javascript




class Solution {
    count(matrix) {
        const numRows = matrix.length;
        const numCols = matrix[0].length;
        let result = 0;
 
        // Iterate through each cell in the matrix
        for (let row = 0; row < numRows; ++row) {
            for (let col = 0; col < numCols; ++col) {
 
                // Check if the current cell is 1
                // Count adjacent cells containing 0
                if (matrix[row][col]) {
 
                    let zeroCount = 0;
 
                    // Check the surrounding 8 cells for zeroes
 
                    // Check top cell
                    if (row - 1 >= 0)
                        zeroCount += matrix[row - 1][col] == 0;
 
                    // Check bottom cell
                    if (row + 1 < numRows)
                        zeroCount += matrix[row + 1][col] == 0;
 
                    // Check left cell
                    if (col - 1 >= 0)
                        zeroCount += matrix[row][col - 1] == 0;
 
                    // Check right cell
                    if (col + 1 < numCols)
                        zeroCount += matrix[row][col + 1] == 0;
 
                    // Check top-left cell
                    if (row - 1 >= 0 && col - 1 >= 0)
                        zeroCount += matrix[row - 1][col - 1] == 0;
 
                    // Check top-right cell
                    if (row - 1 >= 0 && col + 1 < numCols)
                        zeroCount += matrix[row - 1][col + 1] == 0;
 
                    // Check bottom-left cell
                    if (row + 1 < numRows && col - 1 >= 0)
                        zeroCount += matrix[row + 1][col - 1] == 0;
 
                    // Check bottom-right cell
                    if (row + 1 < numRows && col + 1 < numCols)
                        zeroCount += matrix[row + 1][col + 1] == 0;
 
                    // If adjacent zeros are even and nonzero
                    if (!(zeroCount & 1) && zeroCount > 0)
 
                        // Increment the result count
                        result++;
                }
            }
        }
 
        // Return the final count of desired cells
        return result;
    }
}
 
// Driver code
const n = 3, m = 3;
const matrix = [[1, 0, 0], [1, 1, 0], [0, 1, 0]];
 
const ob = new Solution();
 
// Calculate the result using the Solution class
const ans = ob.count(matrix);
 
// Output the result
console.log(ans);


Output

1




Time Complexity: O(N*M)
Auxillary Space: O(1)



Similar Reads

Given a matrix of 'O' and 'X', find the largest subsquare surrounded by 'X'
Given a matrix where every element is either 'O' or 'X', find the largest subsquare surrounded by 'X'. In the below article, it is assumed that the given matrix is also a square matrix. The code given below can be easily extended for rectangular matrices. Examples: Input: mat[N][N] = { {'X', 'O', 'X', 'X', 'X'}, {'X', 'X', 'X', 'X', 'X'}, {'X', 'X'
27 min read
Given a matrix of ‘O’ and ‘X’, replace 'O' with 'X' if surrounded by 'X'
Given a matrix where every element is either ‘O’ or ‘X’, replace 'O' with 'X' if surrounded by 'X'. A 'O' (or a set of 'O') is considered to be surrounded by 'X' if there are 'X' at locations just below, just above, just left, and just right of it. Examples: Input: mat[M][N] = {{'X', 'O', 'X', 'X', 'X', 'X'}, {'X', 'O', 'X', 'X', 'O', 'X'}, {'X', '
15 min read
Counting pairs with condition in even Array halves
Given an array arr[] of integers of size n where n is even, the task is to calculate the number of pairs (i, j) such that i lies in the first half of the array 0 ≤ i &lt; n/2 and j lies in the second half of the array n/2 ≤ j &lt; n and arr[i] ≥ 5*arr[j]. Note: 0-based indexing is used and n is even. Examples: Input: n = 4, arr = {10, 2, 2, 1}Outpu
6 min read
Counting even integers in modified Sequence
Given an integer array A of size N, and Q queries. In each query, you are given an integer X. Create a new sequence X^A[i], say sequence B. For each query find the number of even integers in the modified sequence for a given value of X. Examples: Input: A = {15, 6, 100, 8, 23, 45, 7, 101, 90}, N = 9, Q = 4, X = {3, 7, 10, 60}Output: {5, 5, 4, 4}Exp
11 min read
Counting even decimal value substrings in a binary string
Given a binary string of size N. Count all substring that have even decimal value considering binary to decimal conversion from left to right (For example a substring "1011" is treated as 13) Examples : Input : 101Output : 2Explanation : Substring are : 1, 10, 101, 0, 01, 1 In decimal form : 1, 1, 3, 0, 2, 1 There are only 2 even decimal value subs
9 min read
Average of even numbers till a given even number
Given an even number n, find the average of even numbers from 1 to n.Examples : Input : 10 Output : 6 Explanation: (2 + 4 + 6 + 8 + 10 )/5 = 30/5 = 6 Input : 100 Output : 51 Method 1 We can calculate average by adding each even numbers till n and then dividing sum by count. C/C++ Code // Program to find average of even numbers // till a given even
7 min read
Sum of even numbers at even position
Given an array of size n. The problem is to find the sum of numbers that are even and are at even index. Examples: Input : arr[] = {5, 6, 12, 1, 18, 8} Output : 30 Explanation: Here, n = 6 Now here are index and numbers as: index-&gt;arr[index] 0-&gt;5, 1-&gt;6, 2-&gt;12, 3-&gt;1, 4-&gt;18, 5-&gt;8 so, number which are even and are at even indices
11 min read
Print even positioned nodes of even levels in level order of the given binary tree
Given a binary tree, print even positioned nodes of even level in level order traversal. The root is considered at level 0, and the left most node of any level is considered as a node at position 0. Examples: Input: 1 / \ 2 3 / \ \ 4 5 6 / \ 7 8 / \ 9 10 Output: 1 4 6 9 Input: 2 / \ 4 15 / / 45 17 Output: 2 45 Approach: To print nodes level by leve
8 min read
Count of integers in a range which have even number of odd digits and odd number of even digits
Given a range [L, R], the task is to count the numbers which have even number of odd digits and odd number of even digits. For example, 8 has 1 even digit and 0 odd digit - Satisfies the condition since 1 is odd and 0 is even.545 has 1 even digit and 2 odd digits - Satisfies the condition since 1 is odd and 2 is even.4834 has 3 even digits and 1 od
11 min read
Check if a number has an odd count of odd divisors and even count of even divisors
Given an integer N, the task is to check if N has an odd number of odd divisors and even number of even divisors. Examples: Input: N = 36Output: YesExplanation:Divisors of 36 = 1, 2, 3, 4, 6, 9, 12, 18, 36Count of Odd Divisors(1, 3, 9) = 3 [Odd]Count of Even Divisors(2, 4, 6, 12, 18, 36) = 6 [Even] Input: N = 28Output: No Naive Approach: The idea i
9 min read
Practice Tags :