The Maze

There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolling updownleft or rightbut 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.

思路:球选择一个方向,然后一直走到头,这里tricky的地方就是,要用while循环判断下一个点是否合法来模拟一直走。while(isvalid(maz, nx + dx[k], ny + dy[k]) ,isvalid是判断是否走到墙的位置;T:O(M*N) , S:O(M*N)

class Solution {
   
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        Queue<int[]> queue = new LinkedList<int[]>();
        queue.offer(start);
        
        int[][] dirs = new int[][] {{0,1},{0,-1}, {-1,0},{1,0}};
        int m = maze.length;
        int n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        
        while(!queue.isEmpty()) {
            int[] node = queue.poll();
            int x = node[0];
            int y = node[1];
            if(x == destination[0] && y == destination[1]) {
                return true;
            }
            if(visited[x][y]) {
                continue;
            }
            visited[x][y] = true;
            
            for(int[] dir: dirs) {
                int nx = x;
                int ny = y;
                while(isvalid(nx + dir[0], ny + dir[1], maze)) {
                    nx += dir[0];
                    ny += dir[1];
                }
                queue.offer(new int[]{nx, ny});
            }
        }
        return false;
    }
    
    private boolean isvalid(int x, int y, int[][] maze) {
        int m = maze.length;
        int n = maze[0].length;
        return (0 <= x && x < m && 0 <= y && y < n && maze[x][y] != 1);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值