Special Positions in a Binary Matrix LeetCode Problem
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).
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.
class Solution {
public int numSpecial(int[][] mat) {
int row = mat.length; // Number of rows in the matrix
int col = mat[0].length; // Number of columns in the matrix
// Arrays to store the count of 1s in each row and column
int[] row_count = new int[row]; // Stores count of 1s in each row
int[] col_count = new int[col]; // Stores count of 1s in each column
// First pass: Count the number of 1s in each row and column
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (mat[i][j] == 1) {
row_count[i]++; // Increase count of 1s in this row
col_count[j]++; // Increase count of 1s in this column
}
}
}
int special = 0; // To store the count of special positions
// Second pass: Check for special positions
for (int i = 0; i < row; i++) {
if (row_count[i] == 1) { // If this row has exactly one '1'
for (int j = 0; j < col; j++) {
if (col_count[j] == 1 && mat[i][j] == 1) { // If this column also has exactly one '1'
special++; // Found a special position
}
}
}
}
return special; // Return the count of special positions
}
}
Comments
Post a Comment