Description
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).
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.lengthn == mat[i].length1 <= m, n <= 100mat[i][j]is either0or1.
Solutions
This function finds the count of special positions in a matrix where a special position is a 1 that is the only 1 in its row and the only 1 in its column. It first traverses the entire matrix to count how many 1s appear in each row and column using two Map objects, and stores the positions of all 1s in an array called found. Then it iterates through the found positions and checks if each one is the only 1 in its row (count = 1) and the only 1 in its column (count = 1), incrementing a result counter for each position that satisfies both conditions.
/**
* @param {number[][]} mat
* @return {number}
*/
var numSpecial = function(mat) {
const m = mat.length;
const n = mat[0].length;
const rows = new Map();
const cols = new Map();
const found = [];
for (let row = 0; row < m; row++) {
for (let col = 0; col < n; col++) {
if (mat[row][col] === 1) {
rows.set(row, (rows.get(row) || 0) + 1);
cols.set(col, (cols.get(col) || 0) + 1);
found.push([row, col]);
}
}
}
let res = 0;
for (const [row, col] of found) {
if (rows.get(row) === 1 && cols.get(col) === 1) {
res++;
}
}
return res;
};