题目
代码
class Solution {
public:
vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) {
vector<int> ans;
vector<bool> close(lamps.size(),false);
for(int i=0;i<queries.size();i++){
int x=queries[i][0],y=queries[i][1];
bool flag=false;
for(int j=0;j<lamps.size();j++){
if(close[j]==true) continue;
int xx=lamps[j][0],yy=lamps[j][1];
if(abs(x-xx)<=1 && abs(y-yy)<=1)
close[j]=true;
if(!flag && (x==xx || y==yy || abs(x-xx)==abs(y-yy))){
// cout<<x<<' '<<y<<' '<<xx<<' '<<yy<<endl;
ans.push_back(1);
flag=true;
}
}
if(!flag) ans.push_back(0);
}
return ans;
}
};
思路 哈希表+线映射
用四个哈希表分别存储行、列、正对角线、反对角线,遍历每个灯,把它所在的行、列、正反对角线中亮灯的个数+1.正对角线用x-y表示,反对角线用x+y表示。由于会有重复,需要把灯也用哈希表存储下来,变二维为一维,用x*n+y表示。每次查询,就检查这个位置所在的行、列、正对角线、反对角线是否在哈希表里,并且把这个位置灯移除哈希表。
代码
class Solution {
public:
int dirs[9][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,0},{0,1},{1,-1},{1,0},{1,1}};
vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) {
unordered_map<int,int> row,col,left,right;
unordered_set<long> hash;
vector<int> ans;
for(auto &lamp:lamps){
int x=lamp[0],y=lamp[1];
if(hash.count((long)x*n+y))
continue;
increase(row,x);
increase(col,y);
increase(left,x-y);
increase(right,x+y);
hash.insert((long)x*n+y);
}
for(auto &query:queries){
int x=query[0],y=query[1];
ans.push_back(row.count(x) || col.count(y) || left.count(x-y) || right.count(x+y));
for(int i=0;i<9;i++){
int xx=x+dirs[i][0],yy=y+dirs[i][1];
if(xx<0 || xx>=n || yy<0 || yy>=n) continue;
if(hash.count((long)xx*n+yy)){
decrease(row,xx);
decrease(col,yy);
decrease(left,xx-yy);
decrease(right,xx+yy);
hash.erase((long)xx*n+yy);
}
}
}
return ans;
}
void increase(unordered_map<int,int>& map,int value){
if(map.count(value))
map[value]++;
else
map[value]=1;
return;
}
void decrease(unordered_map<int,int>& map,int value){
if(map[value]==1)
map.erase(value);
else
map[value]--;
return;
}
};