迷宫算法总结(最短路径)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;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值