Skip to content

Commit 2927315

Browse files
committed
feat: add solutions to lc problem: No.2503
No.2503.Maximum Number of Points From Grid Queries
1 parent b96c5e2 commit 2927315

File tree

2 files changed

+70
-0
lines changed

2 files changed

+70
-0
lines changed

solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,6 +93,41 @@ class Solution:
9393
return ans
9494
```
9595

96+
```python
97+
class Solution:
98+
def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:
99+
def find(x):
100+
if p[x] != x:
101+
p[x] = find(p[x])
102+
return p[x]
103+
104+
def union(a, b):
105+
pa, pb = find(a), find(b)
106+
if pa == pb:
107+
return
108+
p[pa] = pb
109+
size[pb] += size[pa]
110+
111+
m, n = len(grid), len(grid[0])
112+
arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n))
113+
k = len(queries)
114+
ans = [0] * k
115+
p = list(range(m * n))
116+
size = [1] * len(p)
117+
j = 0
118+
for i, v in sorted(enumerate(queries), key=lambda x: x[1]):
119+
while j < len(arr) and arr[j][0] < v:
120+
_, a, b = arr[j]
121+
for x, y in pairwise((-1, 0, 1, 0, -1)):
122+
c, d = a + x, b + y
123+
if 0 <= c < m and 0 <= d < n and grid[c][d] < v:
124+
union(a * n + b, c * n + d)
125+
j += 1
126+
if grid[0][0] < v:
127+
ans[i] = size[find(0)]
128+
return ans
129+
```
130+
96131
### **Java**
97132

98133
<!-- 这里可写当前语言的特殊实现逻辑 -->

solution/2500-2599/2503.Maximum Number of Points From Grid Queries/README_EN.md

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,41 @@ class Solution:
7575
return ans
7676
```
7777

78+
```python
79+
class Solution:
80+
def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]:
81+
def find(x):
82+
if p[x] != x:
83+
p[x] = find(p[x])
84+
return p[x]
85+
86+
def union(a, b):
87+
pa, pb = find(a), find(b)
88+
if pa == pb:
89+
return
90+
p[pa] = pb
91+
size[pb] += size[pa]
92+
93+
m, n = len(grid), len(grid[0])
94+
arr = sorted((grid[i][j], i, j) for i in range(m) for j in range(n))
95+
k = len(queries)
96+
ans = [0] * k
97+
p = list(range(m * n))
98+
size = [1] * len(p)
99+
j = 0
100+
for i, v in sorted(enumerate(queries), key=lambda x: x[1]):
101+
while j < len(arr) and arr[j][0] < v:
102+
_, a, b = arr[j]
103+
for x, y in pairwise((-1, 0, 1, 0, -1)):
104+
c, d = a + x, b + y
105+
if 0 <= c < m and 0 <= d < n and grid[c][d] < v:
106+
union(a * n + b, c * n + d)
107+
j += 1
108+
if grid[0][0] < v:
109+
ans[i] = size[find(0)]
110+
return ans
111+
```
112+
78113
### **Java**
79114

80115
```java

0 commit comments

Comments
 (0)