[InterviewBit] Queen Attack

Queen Attack

  • Time :
  • Space :
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
vector<vector<int>> Solution::queenAttack(vector<string> &A) {
int n = A.size(), m = A[0].length();
vector<int> r1(n), c1(m);
unordered_map<int, int> dig1, adig1;
vector<int> r2(n), c2(m);
unordered_map<int, int> dig2, adig2;
auto add = [&](int i, int j, int v) {
r1[i] += v;
c1[j] += v;
dig1[i - j] += v;
adig1[i + j] += v;
};
auto add2 = [&](int i, int j, int v) {
r2[i] += v;
c2[j] += v;
dig2[i - j] += v;
adig2[i + j] += v;
};
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j] == '0') continue;
add(i,j,1);
}
}
vector<vector<int>> res(n,vector<int>(m));
for(int i = 0; i < n; i++) {
for(int j = 0; j < m; j++) {
if(A[i][j] == '1') add(i,j,-1);
res[i][j] = (r1[i] > 0) + (r2[i] > 0) + (c1[j] > 0) + (c2[j] > 0) + (dig1[i-j] > 0) + (dig2[i-j] > 0) + (adig1[i + j] > 0) + (adig2[i + j] > 0);
if(A[i][j] == '1') add2(i,j,1);
}
}
return res;
}
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/10/17/PS/interviewbit/queen-attack/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.