迷宫算法总结(最短路径)BFS宽度优先

使用bfs宽度优先。
根据 leetCode的单词搜索题https://leetcode-cn.com/problems/word-search/得到思路。

class Solution {
    public static void main(String[] args) {
        char[][] migong =new char[][] { 
            {'s','#','#'},
            {'.','.','.'},
            {'.','.','e'}
        
        };
        
        new Solution().exist(migong,0,0,2,2);
        System.out.println(lengthMax);
    }
    private static int length=0;
    private static int lengthMax=Integer.MAX_VALUE;
    
     /**
     * 
     * @param board
     * @param startI 起点
     * @param startJ 起点
     * @param endI 终点
     * @param endJ 终点
     * @return
     */
    public boolean exist(char[][] board,int startI,int startJ,int endI,int endJ) {
        int h = board.length, w = board[0].length;
        // 用于表示走过的格子,就不能重复走
        boolean[][] visited = new boolean[h][w];
        boolean flag = check(board, visited, startI, startJ, endI,endJ);
        if (flag) {
            return true;
        }
        return false;
    }

    public boolean check(char[][] board, boolean[][] visited, int i,int j,int endI,int endJ) {

        length++;
        visited[i][j] = true;
        int[][] directions = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
        boolean result = false;
        for (int[] dir : directions) {
            int newi = i + dir[0], newj = j + dir[1];
            if (newi >= 0 && newi < board.length && newj >= 0 && newj < board[0].length
                    && board[newi][newj]!='#') {
                if (!visited[newi][newj]) {
                    if (newi==endI && newj==endJ) {
                        lengthMax = Math.min(length, lengthMax);
                        break;
                    }
                    boolean flag = check(board, visited, newi, newj, endI,endJ);
                    if (flag) {
                        result = true;
                        break;
                    }
                }
            }
        }
        visited[i][j] = false;
        
        --length;
        return result;
    }
}
BFS宽度优先搜索)算法常被用于解决迷宫问题中的最短路径问题。该算法基于队列的实现方式,可以快速搜索出从起点到达终点的最短路径。 具体来说,BFS算法的步骤如下: 1. 创建一个队列,并将起点加入队列中。 2. 创建一个二维数组来记录迷宫中每个位置的状态,例如是否已被访问过或者是墙壁等。 3. 使用循环来遍历队列中的元素,直到队列为空。 4. 在循环中,首先从队列中取出一个节点,并标记该节点为已访问。 5. 然后检查该节点的上、下、左、右四个方向的相邻节点,如果相邻节点是可行的且未被访问过,则将其加入队列中,并记录其距离起点的步数。 6. 重复步骤4和步骤5,直到找到终点或者遍历完所有可行的节点。 7. 如果找到终点,则可以通过回溯找到最短路径。 需要注意的是,在BFS算法中,我们需要用一个二维数组来记录每个节点的状态,这样可以避免重复访问节点和处理墙壁等不可行的节点。 总结起来,BFS算法通过队列的方式,逐层遍历迷宫中的节点,直到找到终点。在遍历过程中,通过记录每个节点距离起点的步数,可以求解出最短路径。 参考文献: BFS 算法是一种基于队列实现的搜索算法,常用于解决图论问题和迷宫问题。 BFS(Breadth First Search,广度优先搜索)是一种基于队列实现的搜索算法,常用于解决图论问题和迷宫问题。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值