499. The Maze III

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up (u), down (d), left (l) or right ®, but it won’t stop rolling until hitting a wall. When the ball stops, it could choose the next direction. There is also a hole in this maze. The ball will drop into the hole if it rolls on to the hole.

Given the ball position, the hole position and the maze, find out how the ball could drop into the hole by moving the shortest distance. The distance is defined by the number of empty spaces traveled by the ball from the start position (excluded) to the hole (included). Output the moving directions by using ‘u’, ‘d’, ‘l’ and ‘r’. Since there could be several different shortest ways, you should output the lexicographically smallest way. If the ball cannot reach the hole, output “impossible”.

The maze is represented by a binary 2D array. 1 means the wall and 0 means the empty space. You may assume that the borders of the maze are all walls. The ball and the hole coordinates are represented by row and column indexes.

Example 1:

Input 1: a maze represented by a 2D array

0 0 0 0 0
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 1 0 0 0

Input 2: ball coordinate (rowBall, colBall) = (4, 3)
Input 3: hole coordinate (rowHole, colHole) = (0, 1)

Output: “lul”

Explanation: There are two shortest ways for the ball to drop into the hole.
The first way is left -> up -> left, represented by “lul”.
The second way is up -> left, represented by ‘ul’.
Both ways have shortest distance 6, but the first way is lexicographically smaller because ‘l’ < ‘u’. So the output is “lul”.
在这里插入图片描述
Example 2:

Input 1: a maze represented by a 2D array

0 0 0 0 0
1 1 0 0 1
0 0 0 0 0
0 1 0 0 1
0 1 0 0 0

Input 2: ball coordinate (rowBall, colBall) = (4, 3)
Input 3: hole coordinate (rowHole, colHole) = (3, 0)

Output: “impossible”

Explanation: The ball cannot reach the hole.
在这里插入图片描述

Note:

  1. There is only one ball and one hole in the maze.
  2. Both the ball and hole exist on an empty space, and they will not be at the same position initially.
  3. The given maze does not contain border (like the red rectangle in the example pictures), but you could assume the border of the maze are all walls.
  4. The maze contains at least 2 empty spaces, and the width and the height of the maze won’t exceed 30.

方法1: bfs

grandyang:http://www.cnblogs.com/grandyang/p/6746528.html
思路:

在用一个dist来记录最短距离的同时,还要用path来记录获得这个最短距离的路径,用到了降维的trick。每次滚动的终止条件可能是遇到坑了,此时不用后退,直接比较是否能取代当前最优解(注意如果距离和当前最短距离相等要按照字母序优先选择)。滚动的终止也可能是遇到墙了,此时要后退一步,并且以相似比较方法决定是否取代停止点的最短距离和最优解。最后如果最优解没有被更新则为空,返回impossible。

class Solution {
public:
    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
        int m = maze.size(), n = maze[0].size();
        vector<vector<int>> dists(m, vector<int>(n, INT_MAX)); 
        vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
        vector<char> way{'l','u','r','d'};
        unordered_map<int, string> map; 
        queue<pair<int, int>> que; 
        dists[ball[0]][ball[1]] = 0;
        que.push({ball[0], ball[1]}); 
        string ans;
        while(!que.empty()){
            pair<int,int> t = que.front();  que.pop(); 
            for(int i = 0; i < 4; i++){
                int x = t.first, y = t.second, d = dists[x][y]; 
                string path = map[x * n + y]; 
                while(x >= 0 && x < m && y >= 0 && y < n && maze[x][y] != 1 
                      && (x != hole[0] || y != hole[1])){
                    x += dirs[i][0], y += dirs[i][1]; 
                    d++; 
                }
                path.push_back(way[i]); 
                
                if(x == hole[0] && y == hole[1]){
                    if(d < dists[x][y]){
                        dists[x][y] = d;
                        map[x * n + y] = path;
                        ans = path; 
                    }else if(d == dists[x][y] && ans > path){
                        ans = path; 
                    }
                }else{
                    x -= dirs[i][0]; y -= dirs[i][1]; d--; 
                    if(d < dists[x][y]){
                        dists[x][y] = d; 
                        map[x * n +y] = path; 
                        que.push({x, y}); 
                    }else if( d == dists[x][y] && path < map[x * n + y]){
                        map[x * n + y] = path; 
                        que.push({x, y}); 
                    }
                }
            }
            
        }
        
        return ans.size() > 0? ans : "impossible"; 
    }
};

方法2: dfs

grandyang: http://www.cnblogs.com/grandyang/p/6746528.html

class Solution {
public:
    vector<vector<int>> dirs{{0,-1},{-1,0},{0,1},{1,0}};
    vector<char> way{'l','u','r','d'};
    string findShortestWay(vector<vector<int>>& maze, vector<int>& ball, vector<int>& hole) {
        int m = maze.size(), n = maze[0].size();
        vector<vector<int>> dists(m, vector<int>(n, INT_MAX));
        unordered_map<int, string> u;
        dists[ball[0]][ball[1]] = 0;
        helper(maze, ball[0], ball[1], hole, dists, u);
        string res = u[hole[0] * n + hole[1]];
        return res.empty() ? "impossible" : res;
    }
    void helper(vector<vector<int>>& maze, int i, int j, vector<int>& hole, vector<vector<int>>& dists, unordered_map<int, string>& u) {
        if (i == hole[0] && j == hole[1]) return;
        int m = maze.size(), n = maze[0].size();
        for (int k = 0; k < 4; ++k) {
            int x = i, y = j, dist = dists[x][y];
            string path = u[x * n + y];
            while (x >= 0 && x < m && y >= 0 && y < n && maze[x][y] == 0 && (x != hole[0] || y != hole[1])) {
                x += dirs[k][0]; y += dirs[k][1]; ++dist;
            }
            if (x != hole[0] || y != hole[1]) {
                x -= dirs[k][0]; y -= dirs[k][1]; --dist;
            }
            path.push_back(way[k]);
            if (dists[x][y] > dist) {
                dists[x][y] = dist;
                u[x * n + y] = path;
                helper(maze, x, y, hole, dists, u);
            } else if (dists[x][y] == dist && u[x * n + y].compare(path) > 0) {
                u[x * n + y] = path;
                helper(maze, x, y, hole, dists, u);
            }
        }
    }
};

方法3: Dijkstra

思路:

class Solution {
  struct Coordinate {
    int x, y, dist;
    string moves;

    Coordinate( int x, int y, int dist, string moves )
      : x( x ), y( y ), dist( dist ), moves( moves ) {}
  };

  struct Comparator {
    bool operator()( const Coordinate& lhs, const Coordinate& rhs ) {
      // put object with smaller distance up front
      if ( lhs.dist != rhs.dist ) {
        // put rhs up front in the priority queue
        return lhs.dist > rhs.dist;
      }
      // provided both have the same distance, then return true
      // if rhs compares lexicographically less than lhs
      return lhs.moves > rhs.moves;
      // equivalent to
      // return std::lexicographical_compare
      // ( rhs.moves.begin(), rhs.moves.end(),
      //   lhs.moves.begin(), lhs.moves.end() );
    }
  };

public:
  string findShortestWay( const vector<vector<int>>& maze,
                          const vector<int>& ball, const vector<int>& hole ) {
    const int m = maze.size(), n = maze[ 0 ].size();
    const vector<array<int, 2>> dirs{{1, 0}, {0, -1}, {0, 1}, {-1, 0}};
    const vector<char> dirc{'d', 'l', 'r', 'u'};

    vector<vector<bool>> bvisited( m, vector<bool>( n, false ) );
    priority_queue<Coordinate, vector<Coordinate>, Comparator> pq;
    pq.emplace( ball[ 0 ], ball[ 1 ], 0, "" );

    while ( !pq.empty() ) {
      const Coordinate& curr = pq.top();
      const int         cx = curr.x, cy = curr.y, cdist = curr.dist;
      const string      cmoves = curr.moves;
      pq.pop();

      if ( cx == hole[ 0 ] && cy == hole[ 1 ] ) {
        return cmoves;
      }

      if ( !bvisited[ cx ][ cy ] ) {
        bvisited[ cx ][ cy ] = true;
        for ( int idir = 0; idir < 4; idir++ ) {
          const auto& dir = dirs[ idir ];
          int         nx = cx, ny = cy, dis = cdist;
          while ( nx >= 0 && nx < m && ny >= 0 && ny < n &&
                  maze[ nx ][ ny ] == 0 ) {
            nx += dir[ 0 ];
            ny += dir[ 1 ];
            dis++;
            if ( nx == hole[ 0 ] && ny == hole[ 1 ] ) {
              pq.emplace( nx, ny, dis, cmoves + dirc[ idir ] );
              continue;
            }
          }
          // back up one step from wall
          nx -= dir[ 0 ];
          ny -= dir[ 1 ];
          dis--;
          pq.emplace( nx, ny, dis, cmoves + dirc[ idir ] );
        }
      }
    }
    return "impossible";
  }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值