Description
Submission
- No quick solution, for each one of the 8 directions, find the closest obstacle.
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
// Complete the queensAttack function below.
int queensAttack(int n, int k, int r_q, int c_q, vector<vector<int>> obstacles) {
vector<int> dist(8); // distance to the queen(min)
dist[0] = n - c_q;
dist[1] = min(n - c_q, n - r_q);
dist[2] = n - r_q;
dist[3] = min(c_q - 1, n - r_q);
dist[4] = c_q - 1;
dist[5] = min(c_q - 1, r_q - 1);
dist[6] = r_q - 1;
dist[7] = min(r_q - 1, n - c_q);
// find the closet ones in each of the 8 directions
for(int i = 0; i < obstacles.size(); ++i) {
int r = obstacles[i][0];
int c = obstacles[i][1];
int dr = r_q - r;
int dc = c_q - c;
if(dr == 0 || dc == 0 || dr == dc || dr == -dc) {
// right
if(dr == 0 && dc < 0 && -dc < dist[0] + 1)
dist[0] = -dc - 1;
// upper right
if(dr == dc && dr < 0 && -dr < dist[1] + 1)
dist[1] = -dr - 1;
// upper
if(dc == 0 && dr < 0 && -dr < dist[2] + 1)
dist[2] = -dr - 1;
// upper left
if(dc == -dr && dc > 0 && dc < dist[3] + 1)
dist[3] = dc - 1;
// left
if(dr == 0 && dc > 0 && dc < dist[4] + 1)
dist[4] = dc -1;
// lower left
if(dr == dc && dc > 0 && dc < dist[5] + 1)
dist[5] = dc - 1;
// lower
if(dc == 0 && dr > 0 && dr < dist[6] + 1)
dist[6] = dr - 1;
// lower right
if(dr == -dc && dr > 0 && dr < dist[7] + 1)
dist[7] = dr - 1;
}
}
// calculate the total
int total = 0;
for(int i = 0; i < 8; i++) {
total += dist[i];
}
return total;
}
int main()
{
int n; cin >> n;
int k; cin >> k;
int r_q; cin >> r_q;
int c_q; cin >> c_q;
vector<vector<int>> obstacles(k);
for (int i = 0; i < k; i++) {
obstacles[i].resize(2);
for (int j = 0; j < 2; j++) {
cin >> obstacles[i][j];
}
cin.ignore(numeric_limits<streamsize>::max(), '\n');
}
int result = queensAttack(n, k, r_q, c_q, obstacles);
cout << result << "\n";
return 0;
}