-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy path1197.cpp
More file actions
33 lines (30 loc) · 1.21 KB
/
1197.cpp
File metadata and controls
33 lines (30 loc) · 1.21 KB
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
class Solution {
public:
const int MAX_WIDTH = 304;
int minKnightMoves(int x, int y) {
vector<vector<bool>> visited(MAX_WIDTH * 2 + 1, vector<bool>(MAX_WIDTH * 2 + 1, false));
vector<pair<int, int>> directions = {{1, 2}, {2, 1}, {-1, 2}, {-2, 1}, {1, -2}, {2, -1}, {-1, -2}, {-2, -1}};
queue<pair<int, int>> q;
q.push(make_pair(0, 0));
visited[MAX_WIDTH][MAX_WIDTH] = true;
int move = 0;
while (!q.empty()) {
int n = q.size();
while (n--) {
auto [xx, yy] = q.front();
q.pop();
if (xx == x && yy == y) return move;
for (auto direction : directions) {
int _xx = xx + direction.first;
int _yy = yy + direction.second;
if (_xx <= -MAX_WIDTH || _xx >= MAX_WIDTH || _yy <= -MAX_WIDTH || _yy >= MAX_WIDTH) continue;
if (visited[MAX_WIDTH + _xx][MAX_WIDTH + _yy]) continue;
q.push(make_pair(_xx, _yy));
visited[MAX_WIDTH + _xx][MAX_WIDTH + _yy] = true;
}
}
move++;
}
return -1;
}
};