Skip to content

Commit 8a7ff64

Browse files
committed
feat: solve No.1582
1 parent 5e47b8a commit 8a7ff64

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed
Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# 1582. Special Positions in a Binary Matrix
2+
3+
- Difficulty: Easy.
4+
- Related Topics: Array, Matrix.
5+
- Similar Questions: Difference Between Ones and Zeros in Row and Column.
6+
7+
## Problem
8+
9+
Given an `m x n` binary matrix `mat`, return **the number of special positions in **`mat`**.**
10+
11+
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**).
12+
13+
 
14+
Example 1:
15+
16+
![](https://assets.leetcode.com/uploads/2021/12/23/special1.jpg)
17+
18+
```
19+
Input: mat = [[1,0,0],[0,0,1],[1,0,0]]
20+
Output: 1
21+
Explanation: (1, 2) is a special position because mat[1][2] == 1 and all other elements in row 1 and column 2 are 0.
22+
```
23+
24+
Example 2:
25+
26+
![](https://assets.leetcode.com/uploads/2021/12/24/special-grid.jpg)
27+
28+
```
29+
Input: mat = [[1,0,0],[0,1,0],[0,0,1]]
30+
Output: 3
31+
Explanation: (0, 0), (1, 1) and (2, 2) are special positions.
32+
```
33+
34+
 
35+
**Constraints:**
36+
37+
38+
39+
- `m == mat.length`
40+
41+
- `n == mat[i].length`
42+
43+
- `1 <= m, n <= 100`
44+
45+
- `mat[i][j]` is either `0` or `1`.
46+
47+
48+
49+
## Solution
50+
51+
```javascript
52+
/**
53+
* @param {number[][]} mat
54+
* @return {number}
55+
*/
56+
var numSpecial = function(mat) {
57+
var res = 0;
58+
for (var i = 0; i < mat.length; i++) {
59+
var specialCol = -1;
60+
var hasOnlyOne = false;
61+
for (var j = 0; j < mat[i].length; j++) {
62+
if (mat[i][j] === 1) {
63+
if (specialCol === -1) {
64+
specialCol = j;
65+
hasOnlyOne = true;
66+
} else {
67+
hasOnlyOne = false;
68+
}
69+
}
70+
}
71+
if (!hasOnlyOne) continue;
72+
var isValid = true;
73+
for (var k = 0; k < mat.length; k++) {
74+
if (mat[k][specialCol] === 1 && k !== i) {
75+
isValid = false;
76+
break;
77+
}
78+
}
79+
if (isValid) res += 1;
80+
}
81+
return res;
82+
};
83+
```
84+
85+
**Explain:**
86+
87+
nope.
88+
89+
**Complexity:**
90+
91+
* Time complexity : O(n * m).
92+
* Space complexity : O(1).

0 commit comments

Comments
 (0)