资讯专栏INFORMATION COLUMN

[LeetCode] 490. The Maze (BFS/DFS)

smartlion / 753人阅读

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 1:

Input 1: a maze represented by a 2D array

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

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (4, 4)

Output: true

Explanation: One possible way is : left -> down -> left -> down -> right -> down -> right.

Example 2:

Input 1: a maze represented by a 2D array

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

Input 2: start coordinate (rowStart, colStart) = (0, 4)
Input 3: destination coordinate (rowDest, colDest) = (3, 2)

Output: false

Explanation: There is no way for the ball to stop at the destination.

Note:

There is only one ball and one destination in the maze.
Both the ball and the destination exist on an empty space, and they will not be at the same position initially.
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.
The maze contains at least 2 empty spaces, and both the width and height of the maze won"t exceed 100.

Solution - DFS
class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        int m = maze.length, n = maze[0].length;
        boolean[][] visited = new boolean[m][n];
        return dfs(maze, visited, start, destination);
    }
    private boolean dfs(int[][] maze, boolean[][] visited, int[] start, int[] destination) {
        int row = start[0], col = start[1];
        
        //check boundaries and if the point visited before
        if (row < 0 || row >= maze.length || col < 0 || col >= maze[0].length || visited[row][col]) return false;
        
        //mark as a visited stop point
        visited[row][col] = true;
        
        //if stop point is destination => true
        if (row == destination[0] && col == destination[1]) return true;
        
        //DFS on four directions
        int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
        for (int i = 0; i < 4; i++) {
            int x = row, y = col;
            
            //rolling until out or hit the wall 
            while (x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] != 1) {
                x += dirs[i][0];
                y += dirs[i][1];
            }
            
            //back to the stop point
            x -= dirs[i][0];
            y -= dirs[i][1];
            
            //start another dfs from the stop point
            if (dfs(maze, visited, new int[]{x, y}, destination)) return true;
        }
        return false;
    }
}
Solution - BFS
class Solution {
    public boolean hasPath(int[][] maze, int[] start, int[] destination) {
        int m = maze.length, n = maze[0].length;
        Deque queue = new ArrayDeque<>();
        boolean[][] visited = new boolean[m][n];
        queue.offer(start);
        while (!queue.isEmpty()) {
            int[] cur = queue.poll();
            int row = cur[0], col = cur[1];
            if (row == destination[0] && col == destination[1]) return true;
            if (visited[row][col]) continue;
            visited[row][col] = true;
            int[][] dirs = new int[][]{{1,0},{-1,0},{0,1},{0,-1}};
            for (int[] dir: dirs) {
                int x = row;
                int y = col;
                while (x >= 0 && x < maze.length && y >= 0 && y < maze[0].length && maze[x][y] == 0) {
                    x += dir[0];
                    y += dir[1];
                }
                x -= dir[0];
                y -= dir[1];
                queue.offer(new int[]{x, y});
            }
        }
        return false;
    }
}

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/72454.html

相关文章

  • 490. The Maze && 505. The Maze II

    摘要:题目链接和上一题不一样的是这道题要求最短的路径,普通的遍历和都是可以做的,但是求最短路径的话还是用。这里相当于每个点有至多条相连,每条的就是到墙之前的长度。 490. The Maze 题目链接:https://leetcode.com/problems... 又是图的遍历问题,就是简单的遍历,所以dfs和bfs都可以做,复杂度也是一样的。这道题要求球不能停下来,即使碰到destina...

    BoYang 评论0 收藏0
  • [LintCode/LeetCode] Clone Graph [BFS/DFS]

    摘要:开始看这道题目的时候,没有看懂和的作用。然后对这个放入的结点开始操作遍历的所有,当前遍历到的的叫做。当完成,则中没有新的结点了,退出循环。返回在中更新过的,结束。 Problem Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. We use #...

    fredshare 评论0 收藏0
  • LeetCode 133:克隆图 Clone Graph

    摘要:解题思路涉及到图的遍历无非就是深度优先搜索广度优先搜索,可以先看前几日的这篇文章就需要借助队列实现,可以借助栈也可以直接用递归实现。 题目: 给定无向连通图中一个节点的引用,返回该图的深拷贝(克隆)。图中的每个节点都包含它的值 val(Int) 和其邻居的列表(list[Node])。 Given a reference of a node in a connected undirec...

    Simon 评论0 收藏0
  • The Maze II

    摘要:题目链接一般这种题,给一个起点,给一个终点,最后要求最短的路径,都是用来解。的图不是很大,也能。 The Maze II 题目链接:https://leetcode.com/contest/...一般这种题,给一个起点,给一个终点,最后要求最短的路径,都是用bfs来解。 public class Solution { public String findShortestWay(...

    luffyZh 评论0 收藏0
  • BFS,DFS 算法原理及js实现

    1. 说明 本文所有的算法严格按照《算法导论》,本文将详细的对BFS和DFS进行分析,并提供算法的 js 实现,同时会对创建链表的方式进行优化 2. 图的表示 图的表示分为对顶点集 V 的表示和对边集 E 的表示,这里的重点是如何表示边,边的表示分为邻接矩阵和邻接链表这两种表示方法,邻接矩阵适合表示边稠密的图,其消耗空间为|V|*|V|,如果是无向图,则可以用上三角矩阵或者下三角矩阵来表示,是空间...

    刘德刚 评论0 收藏0

发表评论

0条评论

smartlion

|高级讲师

TA的文章

阅读更多
最新活动
阅读需要支付1元查看
<