2019年11月10日 星期日

The Maze


The Maze

  • Lintcode : 787 / Leetcode : 490
  • Level : Medium

Problem

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling up, down, left or right, but it won't stop rolling until hitting a wall. When the ball stops, it could choose the next direction.

Given the ball's start position, the destination and the maze, determine whether the ball could stop at the destination.

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 start and destination coordinates are represented by row and column indexes.

Example
Example 1:

Input:
map = 
[
 [0,0,1,0,0],
 [0,0,0,0,0],
 [0,0,0,1,0],
 [1,1,0,1,1],
 [0,0,0,0,0]
]
start = [0,4]
end = [3,2]
Output:
false
Example 2:

Input:
map = 
[[0,0,1,0,0],
 [0,0,0,0,0],
 [0,0,0,1,0],
 [1,1,0,1,1],
 [0,0,0,0,0]
]
start = [0,4]
end = [4,4]
Output:
true
Notice
1.There is only one ball and one destination in the maze.
2.Both the ball and the destination 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.
5.The maze contains at least 2 empty spaces, and both the width and height of the maze won't exceed 100.

Concept & Algorithm

Time Complexity & Space Complexity

time : O(avg steps can roll avg stop point)
space: O(m
n)

Answer

class Solution {
public:
    bool hasPath(vector<vector<int>> &maze, vector<int> &start, vector<int> &destination) {
        int m = maze.size(), n = maze[0].size();
        queue<vector<int>> q;
        vector<vector<bool>> isVisited(m, vector<bool>(n, false));
        q.push(start);
        isVisited[start[0]][start[1]] = true;
        while (!q.empty()) {
            vector<int> h = q.front(); q.pop();
            if (h[0] == destination[0] && h[1] == destination[1]) return true;
            for (auto d : dir) {
                vector<int> stop = rolling(maze, d, h);
                if (isVisited[stop[0]][stop[1]]) continue;
                q.push(stop);
                isVisited[stop[0]][stop[1]] = true;
            }
        }
        return false;
    }
    vector<vector<int>> dir = {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};
    vector<int> rolling(vector<vector<int>> &maze, vector<int> d, vector<int> h) {
        int x = h[0], y = h[1];
        while (x >= 0 && y >= 0 && x < maze.size() && y < maze[0].size() && !maze[x][y]) {
            x += d[0];
            y += d[1];
        }
        x -= d[0];
        y -= d[1];
        return {x, y};
    }
};
tags: BFS

沒有留言:

張貼留言

Last Position of Target

Last Position of Target Lintcode : 458 / Leetcode : 34 Level : Easy Problem Find the last position of a target number in a sorted ...