forked from AnasImloul/Leetcode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQueens That Can Attack the King.cpp
32 lines (27 loc) · 1.05 KB
/
Queens That Can Attack the King.cpp
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
class Solution {
public:
vector<vector<int>> queensAttacktheKing(vector<vector<int>>& queens, vector<int>& king)
{
vector<vector<int>> ans;
vector<vector<int>> board(8, vector<int>(8, 0));
for(auto queen: queens) board[queen[0]][queen[1]] = 1;
for(int x=-1; x<=1; x++) // Both loops are for checking in all the 8 possible directions
{
for(int y=-1; y<=1; y++)
{
if(x == 0 and y == 0) continue;
int startx = king[0], starty = king[1];
while(startx >= 0 and startx < 8 and starty >= 0 and starty < 8)
{
if(board[startx][starty] == 1) // If queen is found, append it to ans and break
{
ans.push_back({startx, starty});
break;
}
startx += x, starty += y; // Otherwise keep moving forward in earlier direction
}
}
}
return ans;
}
};