-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path3212.py
More file actions
137 lines (107 loc) · 3.12 KB
/
3212.py
File metadata and controls
137 lines (107 loc) · 3.12 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
"""3212. Count Submatrices With Equal Frequency of X and Y
Given a 2D character matrix grid, where grid[i][j] is either 'X', 'Y', or '.', return the number of submatrices that contain:
grid[0][0]
an equal frequency of 'X' and 'Y'.
at least one 'X'.
Example 1:
Input: grid = [["X","Y","."],["Y",".","."]]
Output: 3
Example 2:
Input: grid = [["X","X"],["X","Y"]]
Output: 0
for Explaination see the question on leetcode and see the image that are explaining well
No submatrix has an equal frequency of 'X' and 'Y'.
Example 3:
Input: grid = [[".","."],[".","."]]
Output: 0
Explanation:
No submatrix has at least one 'X'."""
from typing import List
class Solution:
def numberOfSubmatrices(self, grid: List[List[str]]) -> int:
m, n = len(grid), len(grid[0])
prefix_x = [[0] * n for _ in range(m)]
prefix_y = [[0] * n for _ in range(m)]
for i in range(m):
for j in range(n):
px = 1 if grid[i][j] == 'X' else 0
py = 1 if grid[i][j] == 'Y' else 0
if i > 0:
px += prefix_x[i-1][j]
py += prefix_y[i-1][j]
if j > 0:
px += prefix_x[i][j-1]
py += prefix_y[i][j-1]
if i > 0 and j > 0:
px -= prefix_x[i-1][j-1]
py -= prefix_y[i-1][j-1]
prefix_x[i][j] = px
prefix_y[i][j] = py
count = 0
for i in range(m):
for j in range(n):
x = prefix_x[i][j]
y = prefix_y[i][j]
if x == y and x > 0:
count += 1
return count
# ── Test Runner
def run_tests():
sol = Solution()
tests = [
(
[["X","Y",".","."],["Y",".",".","."]],
3,
"Example 1"
),
(
[["X","X"],["X","Y"]],
0,
"Example 2 — no equal frequency"
),
(
[[".",".","."],[".",".",".",]],
0,
"Example 3 — no X at all"
),
(
[["X"]],
0,
"Single X, no Y"
),
(
[["X","Y"]],
1,
"Single row X,Y"
),
(
[["X","Y","X","Y"]],
2,
"Row: X Y X Y"
),
(
[["X","Y"],["Y","X"]],
2,
"2x2 symmetric grid"
),
]
passed = 0
failed = 0
print("=" * 55)
print(" LeetCode 3212 — Submatrices With Equal Freq X & Y")
print("=" * 55)
for i, (grid, expected, desc) in enumerate(tests, 1):
result = sol.numberOfSubmatrices(grid)
status = "PASS ✓" if result == expected else "FAIL ✗"
if result == expected:
passed += 1
else:
failed += 1
print(f" Test {i}: {status} | {desc}")
if result != expected:
print(f" Expected {expected}, got {result}")
print("=" * 55)
print(f" Results: {passed} passed, {failed} failed")
print("=" * 55)
if __name__ == "__main__":
run_tests()