/** * 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 { 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 vector<vector<int>> step = {{2,1},{1,2},{-2,1},{1,-2},{2,-1},{-1,2},{-1,-2},{-2,-1}}; int n = grid.size(), m = grid[0].size(), res = 0; queue<Point> q; q.push(source); grid[source.x][source.y] = true; while (!q.empty()) { int N = q.size(); res++; while (N > 0) { int r = q.front().x, c = q.front().y; N--; q.pop(); if (r == destination.x && c == destination.y) return res-1; for (int i = 0; i < step.size(); i++){ int new_r = r+step[i][0], new_c = c+step[i][1]; if (new_r >= 0 && new_r < n && new_c >= 0 && new_c < m && !grid[new_r][new_c]) { q.push(Point(new_r,new_c)); grid[new_r][new_c] = true; } } } } return -1;
} };
-------------end of file
thanks for reading-------------