-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy path611.knight-shortest-path.cpp
67 lines (56 loc) · 1.73 KB
/
611.knight-shortest-path.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
/**
* Definition for a point.
* struct Point {
* int x;
* int y;
* Point() : x(0), y(0) {}
* Point(int a, int b) : x(a), y(b) {}
* };
*/
class Solution {
private:
vector<vector<int>> directions = {{1, 2}, {1, -2}, {-1, 2}, {-1, -2}, {2, 1}, {2, -1}, {-2, 1}, {-2, -1}};
bool in_bound(vector<vector<bool>> &grid, int x, int y)
{
return x >= 0 && x < grid.size() && y >= 0 && y < grid[x].size();
}
public:
/**
* @param grid: a chessboard included 0 (false) and 1 (true)
* @param source: a point
* @param destination: a point
* @return: the shortest path
*/
int shortestPath(vector<vector<bool>> &grid, Point &source, Point &destination) {
// write your code here
queue<pair<int, int>> q;
q.push(make_pair(source.x, source.y));
grid[source.x][source.y] = true;
int steps = 0;
while(!q.empty())
{
int size = q.size();
for (auto i = 0; i < size; ++i)
{
pair<int, int> tmp = q.front();
q.pop();
if (tmp.first == destination.x && tmp.second == destination.y)
{
return steps;
}
for (auto i = 0; i < 8; i++)
{
int new_x = tmp.first + directions[i][0];
int new_y = tmp.second + directions[i][1];
if (in_bound(grid, new_x, new_y) && grid[new_x][new_y] == 0)
{
q.push(make_pair(new_x, new_y));
grid[new_x][new_y] = true;
}
}
}
steps++;
}
return -1;
}
};