Skip to content

Commit 1fd19a5

Browse files
authored
Create grid-illumination.py
1 parent f0f449e commit 1fd19a5

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Python/grid-illumination.py

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# Time: O(l + q)
2+
# Space: O(l)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def gridIllumination(self, N, lamps, queries):
9+
"""
10+
:type N: int
11+
:type lamps: List[List[int]]
12+
:type queries: List[List[int]]
13+
:rtype: List[int]
14+
"""
15+
directions = [(0, -1), (0, 1), (-1, 0), (1, 0),
16+
(-1, -1), (1, -1), (1, -1), (1, 1)]
17+
18+
lookup = set()
19+
row = collections.defaultdict(int)
20+
col = collections.defaultdict(int)
21+
diag = collections.defaultdict(int)
22+
anti = collections.defaultdict(int)
23+
24+
for r, c in lamps:
25+
lookup.add((r, c))
26+
row[r] += 1
27+
col[c] += 1
28+
diag[r-c] += 1
29+
anti[r+c] += 1
30+
31+
result = []
32+
for r, c in queries:
33+
if row[r] or col[c] or \
34+
diag[r-c] or anti[r+c]:
35+
result.append(1)
36+
else:
37+
result.append(0)
38+
for d in directions:
39+
nc, nr = r+d[0], c+d[1]
40+
if not (0 <= nr < N and 0 <= nc < N and \
41+
(nr, nc) in lookup):
42+
continue
43+
lookup.remove((nr, nc))
44+
row[nr] -= 1
45+
col[nc] -= 1
46+
diag[nr-nc] -= 1
47+
anti[nr+nc] -= 1
48+
return result

0 commit comments

Comments
 (0)