On a N x N
grid of cells, each cell (x, y)
with 0 <= x < N
and 0 <= y < N
has a lamp.
Initially, some number of lamps are on. lamps[i]
tells us the location of the i
-th lamp that is on. Each lamp that is on illuminates every square on its x-axis, y-axis, and both diagonals (similar to a Queen in chess).
For the i-th query queries[i] = (x, y)
, the answer to the query is 1 if the cell (x, y) is illuminated, else 0.
After each query (x, y)
[in the order given by queries
], we turn off any lamps that are at cell (x, y)
or are adjacent 8-directionally (ie., share a corner or edge with cell (x, y)
.)
Return an array of answers. Each value answer[i]
should be equal to the answer of the i
-th query queries[i]
.
Example 1:
Input: N = 5, lamps = [[0,0],[4,4]], queries = [[1,1],[1,0]]
Output: [1,0]
Explanation:
Before performing the first query we have both lamps [0,0] and [4,4] on.
The grid representing which cells are lit looks like this, where [0,0] is the top left corner, and [4,4] is the bottom right corner:
1 1 1 1 1
1 1 0 0 1
1 0 1 0 1
1 0 0 1 1
1 1 1 1 1
Then the query at [1, 1] returns 1 because the cell is lit. After this query, the lamp at [0, 0] turns off, and the grid now looks like this:
1 0 0 0 1
0 1 0 0 1
0 0 1 0 1
0 0 0 1 1
1 1 1 1 1
Before performing the second query we have only the lamp [4,4] on. Now the query at [1,0] returns 0, because the cell is no longer lit.
Note:
1 <= N <= 10^9
0 <= lamps.length <= 20000
0 <= queries.length <= 20000
lamps[i].length == queries[i].length == 2
思路:记录每个lamp能覆盖的位置,包括
1. 行
2. 列
3. 45度对角线
4. -45度对角线
关键是对应每个点(i,j)要平移(沿着xy轴或者2个对角线方向)到xy轴上去
from collections import defaultdict
class Solution(object):
def gridIllumination(self, N, lamps, queries):
"""
:type N: int
:type lamps: List[List[int]]
:type queries: List[List[int]]
:rtype: List[int]
"""
rows = defaultdict(set)
cols = defaultdict(set)
for i,j in lamps:
rows[i].add((i,j))
cols[j].add((i,j))
xy = defaultdict(set)
yx = defaultdict(set)
for i,j in lamps:
mi = min(i,j)
ii,jj=i-mi,j-mi
xy[(ii,jj)].add((i,j))
mi = min(i,N-1-j)
ii,jj=i-mi,j+mi
yx[(ii,jj)].add((i,j))
def check(i,j):
if len(rows[i]) or len(cols[j]): return True
mi = min(i,j)
ii,jj=i-mi,j-mi
if len(xy[(ii,jj)]): return True
mi = min(i,N-1-j)
ii,jj=i-mi,j+mi
if len(yx[(ii,jj)]): return True
return False
lamps = set([tuple(s) for s in lamps])
def remove(i,j):
if (i,j) not in lamps: return
lamps.remove((i,j))
rows[i].remove((i,j))
cols[j].remove((i,j))
mi = min(i,j)
ii,jj=i-mi,j-mi
xy[(ii,jj)].remove((i,j))
mi = min(i,N-1-j)
ii,jj=i-mi,j+mi
yx[(ii,jj)].remove((i,j))
res = []
for i,j in queries:
if check(i,j): res.append(1)
else: res.append(0)
for di in [-1,0,1]:
for dj in [-1,0,1]:
ii,jj=i+di,j+dj
remove(ii,jj)
return res