Skip to content

Commit 663f476

Browse files
1582. Special Positions in a Binary Matrix
1 parent 2528221 commit 663f476

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
"""
2+
Given a rows x cols matrix mat, where mat[i][j] is either 0 or 1, return
3+
the number of special positions in mat.
4+
5+
A position (i,j) is called special if mat[i][j] == 1 and all other elements
6+
in row i and column j are 0 (rows and columns are 0-indexed).
7+
8+
Example:
9+
Input: mat = [[1,0,0],
10+
[0,0,1],
11+
[1,0,0]]
12+
Output: 1
13+
Explanation: (1,2) is a special position because mat[1][2] == 1 and all
14+
other elements in row 1 and column 2 are 0.
15+
16+
Example:
17+
Input: mat = [[1,0,0],
18+
[0,1,0],
19+
[0,0,1]]
20+
Output: 3
21+
Explanation: (0,0), (1,1) and (2,2) are special positions.
22+
23+
Example:
24+
Input: mat = [[0,0,0,1],
25+
[1,0,0,0],
26+
[0,1,1,0],
27+
[0,0,0,0]]
28+
Output: 2
29+
30+
Example:
31+
Input: mat = [[0,0,0,0,0],
32+
[1,0,0,0,0],
33+
[0,1,0,0,0],
34+
[0,0,1,0,0],
35+
[0,0,0,1,1]]
36+
Output: 3
37+
38+
Constraints:
39+
- rows == mat.length
40+
- cols == mat[i].length
41+
- 1 <= rows, cols <= 100
42+
- mat[i][j] is 0 or 1.
43+
"""
44+
#Difficulty: Easy
45+
#95 / 95 test cases passed.
46+
#Runtime: 220 ms
47+
#Memory Usage: 13.9 MB
48+
49+
#Runtime: 220 ms, faster than 48.49% of Python3 online submissions for Special Positions in a Binary Matrix.
50+
#Memory Usage: 13.9 MB, less than 61.78% of Python3 online submissions for Special Positions in a Binary Matrix.
51+
52+
class Solution:
53+
54+
def numSpecial(self, mat: List[List[int]]) -> int:
55+
count = 0
56+
rows = len(mat)
57+
cols = len(mat[0])
58+
for row in range(rows):
59+
for col in range(cols):
60+
if mat[row][col] == 1 and self.rowCheck(mat, row) and self.colCheck(mat, rows, col):
61+
count += 1
62+
return count
63+
64+
def rowCheck(self, mat, row):
65+
return mat[row].count(1) == 1
66+
67+
def colCheck(self, mat, rows, col):
68+
count = 0
69+
for row in range(rows):
70+
if mat[row][col] == 1:
71+
count += 1
72+
return count == 1

0 commit comments

Comments
 (0)