Find special Positions in a Binary Matrix.

Find special Positions in a Binary Matrix.

Q - Given an m x n binary matrix mat, return the number of special positions in mat. A position (i, j) is called special if mat[i][j] == 1 and all other elements in row i and column j are 0 (rows and columns are 0-indexed).

LeetCode Problem: Link | Click Here

class Solution {
    public int numSpecial(int[][] mat) {

        int count = 0;
        int lenRow = mat.length; // Get the number of rows in the matrix
        int lenCol = mat[0].length; // Get the number of columns in the matrix

        // Iterate through each cell in the matrix
        for (int i = 0; i < lenRow; i++) { // i = row
            for (int j = 0; j < lenCol; j++) { // j = column
                if (mat[i][j] == 1) { // Check if the current cell contains 1 (special element)
                    int spCol = 0;
                    int spRow = 0;

                    // Check the number of 1s in the same column as the current cell
                    for (int k = 0; k < lenRow; k++) {
                        if (mat[k][j] == 1) {
                            spCol++;
                        }
                    }

                    // Check the number of 1s in the same row as the current cell
                    for (int p = 0; p < lenCol; p++) {
                        if (mat[i][p] == 1) {
                            spRow++;
                        }
                    }

                    // If the cell is the sole '1' in its row and column, count it as special.
                    if ((spCol == 1) && (spRow == 1)) {
                        count++;
                    }
                }
            }
        }

        return count; // Return the count of special elements
    }
}

Did you find this article valuable?

Support Perf Insights by becoming a sponsor. Any amount is appreciated!