AM 788. The Maze II

Code(Language:C++) (Judger:cloudjudge-cluster-9)
class Solution {
public:
    /**
     * @param maze: the maze
     * @param start: the start
     * @param destination: the destination
     * @return: the shortest distance for the ball to stop at the destination
     */
    struct node{
        int x, y; 
        node(int x, int y){
            this->x = x; 
            this->y = y; 
        }
    };  
    const vector<int> dx = {-1, 1, 0, 0};
    const vector<int> dy = {0, 0, -1, 1};
    const int dir = 4;
    
    bool canStop(int x, int y, vector<vector<int>> &maze){
        if(x < 0 || y < 0 || x >= maze.size() || y >= maze[0].size() || maze[x][y] == 1){
            return true; 
        } 
        return false; 
    }
    
    int shortestDistance(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination) {
        // write your code here
        const int m = maze.size();
        const int n = maze[0].size(); 
        std::queue<node> q;
        q.push(node(start[0], start[1])); 
        
        vector<vector<int>> dis(m, vector<int>(n, INT_MAX)); // status matrix to save distance along the path 
        
        dis[start[0]][start[1]] = 0; 
        maze[start[0]][start[1]] = 2; 
        
        int res = INT_MAX; 
        while(!q.empty()){
            node tmp = q.front();
            q.pop();
            //if(tmp.x == destination[0] && tmp.y == destination[1]){
            //    res = min(res, dis[tmp.x][tmp.y]); 
            //}
            for(int i = 0; i < dir; i++){
                int newX = tmp.x; 
                int newY = tmp.y; 
                int pathLen = 0; 
                while(!canStop(newX + dx[i], newY + dy[i], maze)){
                    newX += dx[i];
                    newY += dy[i];
                    pathLen++; 
                }
                if(maze[newX][newY] == 2){
                    continue; 
                }
                maze[newX][newY] = 2; 
                q.push(node(newX, newY)); 
                
                dis[newX][newY] = min(dis[newX][newY], dis[tmp.x][tmp.y] + pathLen); // update when shorter distance available 
            }
        }
        //return res == INT_MAX ? -1 : res; 
        return dis[destination[0]][destination[1]] == INT_MAX ? -1 : dis[destination[0]][destination[1]]; 
    }
};

Comments

Popular posts from this blog

算法的比较