The Shortest Route for the lintcode Knight

The Shortest Route for the lintcode Knight

describe

Given the initial position of the knight on the chessboard (a binary matrix of 0 denotes empty 1 denotes obstacles), find the shortest route to the end and return the length of the route. If the knight cannot reach, return to - 1.

Explain

If the knight's position is (x,y), he can reach the following positions next:

(x + 1, y + 2)
(x + 1, y - 2)
(x - 1, y + 2)
(x - 1, y - 2)
(x + 2, y + 1)
(x + 2, y - 1)
(x - 2, y + 1)
(x - 2, y - 1)

Example

Example 1:

Input:
[[0,0,0],
[0,0,0],
[0,0,0]]
source = [2, 0] destination = [2, 2]
Output: 2
Interpretation:
[2,0]->[0,1]->[2,2]
Example 2:

Input:
[[0,1,0],
[0,0,1],
[0,0,0]]
source = [2, 0] destination = [2, 2]
Output: -1

thinking

A queue is used to record all the points that can be reached in step n, and an 8*2 two-dimensional array step is used to represent the way the knight moves forward.

For all points in the current queue, step is traversed to get all new points. If it meets the requirements and does not pass through this point, it can join the queue and change the point in grid to true, and traverse the point in the next loop. If a point is found to be the end point, the number of steps returned.

Code

/**
 * 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;
        
    }
};

Posted by amarquis on Tue, 26 Mar 2019 08:42:28 -0700