Special Positions in a Binary Matrix

Updated on 11 July, 2025
Special Positions in a Binary Matrix header image

Problem Statement

Given a binary matrix mat of dimensions m x n, the task is to determine the number of special positions within this matrix. A position (i, j) in the matrix qualifies as special if the value at that position is 1, and all other values in the same row i and column j are 0. This problem combines aspects of matrix manipulation and condition checking to identify these unique positions, enhancing both data comprehension and analytical skills.

Examples

Example 1

Input:

mat = [[1,0,0],[0,0,1],[1,0,0]]

Output:

1

Explanation:

(1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.

Example 2

Input:

mat = [[1,0,0],[0,1,0],[0,0,1]]

Output:

3

Explanation:

(0, 0), (1, 1) and (2, 2) are special positions.

Constraints

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 100
  • mat[i][j] is either 0 or 1.

Approach and Intuition

The approach to solving this problem can be broken into several logical steps:

  1. Read the matrix dimensions, m for rows, and n for columns.
  2. Use a variable to keep track of the count of special positions, initialized to 0.
  3. Iterate through each cell of the matrix.
  4. For a cell containing 1, verify its uniqueness in its row and column:
    • Check all other cells in the row i to ensure they are 0.
    • Check all other cells in column j to ensure they are 0.
  5. If a cell (i, j) meets these conditions, increment the counter of special positions.
  6. Return the final count.

This method ensures that we perform a focused check on matrix positions that potentialy could be special, based on the condition given. This is an efficient manner to handle the problem within the provided constraints and guarantees a complete search without unnecessary computations.

Solutions

  • C++
cpp
class Solution {
public:
    int countSpecialCells(vector<vector<int>>& matrix) {
        int rows = matrix.size();
        int cols = matrix[0].size();
        vector<int> rowSum(rows, 0);
        vector<int> colSum(cols, 0);
            
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 1) {
                    rowSum[i]++;
                    colSum[j]++;
                }
            }
        }
            
        int specialCount = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 1) {
                    if (rowSum[i] == 1 && colSum[j] == 1) {
                        specialCount++;
                    }
                }
            }
        }
            
        return specialCount;
    }
};

The provided C++ solution aims to solve the problem of counting special positions in a binary matrix. A position (i, j) in a matrix is termed special if both the row i and column j contain exactly one 1.

The solution involves the following steps:

  1. Calculate the size of the rows and columns of the matrix.
  2. Create two vectors, rowSum and colSum, initialized to zero. These arrays are used to track the count of 1s in each row and column respectively.
  3. Traverse the matrix and update the counts in rowSum and colSum for each 1 encountered.
  4. Initialize specialCount to zero. This variable will keep track of the number of special positions found.
  5. Perform a second pass over the matrix to find cells where the value is 1 and both the respective row and column contain exactly one 1. For each such cell found, increment specialCount.
  6. Return specialCount, which now contains the number of special positions in the matrix.

By efficiently counting the number of 1s in each row and column initially, the solution reduces the amount of computation needed when looking for special positions, allowing for performance gains, especially with large matrices.

  • Java
java
class Solution {
    public int countSpecialElements(int[][] matrix) {
        int rows = matrix.length;
        int cols = matrix[0].length;
        int[] rowOnes = new int[rows];
        int[] colOnes = new int[cols];
    
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 1) {
                    rowOnes[i]++;
                    colOnes[j]++;
                }
            }
        }
    
        int count = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (matrix[i][j] == 1) {
                    if (rowOnes[i] == 1 && colOnes[j] == 1) {
                        count++;
                    }
                }
            }
        }
    
        return count;
    }
}

The given Java solution addresses the problem of finding special positions in a binary matrix. A position in the matrix is considered special if it contains the value 1 and is the only 1 in both its row and column.

Here's a summary of how the solution works:

  • Define the number of rows and columns in the matrix.
  • Initialize arrays rowOnes and colOnes to keep track of the count of 1s in each row and column, respectively.
  • Loop through the matrix to fill up rowOnes and colOnes by iterating over every element. Increment the respective counters in rowOnes and colOnes each time a 1 is found.
  • Initialize a counter count to zero which will store the number of special positions.
  • Iterate through the matrix again, this time to check for special positions. For each 1 found in the matrix, check if it is the only 1 in its row and column using the rowOnes and colOnes arrays. If true, increment the count.
  • Return the count which now represents the number of special positions in the matrix.

This approach efficiently utilizes two passes through the matrix: one for counting occurrences of 1s and another for checking the special condition, making it straightforward to understand and implement.

  • Python
python
class Solution:
    def countSpecialNumbers(self, matrix: List[List[int]]) -> int:
        rows = len(matrix)
        cols = len(matrix[0])
        row_sum = [0] * rows
        col_sum = [0] * cols
            
        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == 1:
                    row_sum[i] += 1
                    col_sum[j] += 1
                        
        special_count = 0
        for i in range(rows):
            for j in range(cols):
                if matrix[i][j] == 1 and row_sum[i] == 1 and col_sum[j] == 1:
                    special_count += 1
    
        return special_count

This solution focuses on identifying special positions in a binary matrix. A position is considered special if the value is '1' and it is the only '1' in its row and column. The process employs a Python program structured within a class Solution with a method named countSpecialNumbers that takes a matrix as input and returns the count of special positions.

  • The solution first determines the number of rows and columns in the input matrix.
  • Two lists, row_sum and col_sum, are initialized to store the count of '1's in each row and column.
  • Count of '1's for each row and column is calculated through nested loops.
  • Another set of nested loops checks each element if it is '1' and verifies if its corresponding row and column counters remain '1'.
  • The sum of all positions meeting these criteria is then returned as the count of special positions.

Adopt the following step-by-step approach to implement this solution:

  1. Calculate the dimensions of the matrix (rows and columns).
  2. Initialize the row_sum and col_sum lists to zero.
  3. Populate these lists with the count of '1's present in each row and column respectively.
  4. Iterate over the matrix to count elements that are '1' and are the unique ones in their respective row and column.
  5. Return the count of these special positions.

This solution will effectively allow you to identify and count special positions in a given binary matrix efficiently.

Comments

No comments yet.