迷宫问题, 华为

深度优先遍历搜索。
从(0,0)开始整个矩阵矩阵,只能向上向下,向左向右走,且前方没有障碍物并且没有走过。遍历过程需要记录下来当前点是从哪个点(如果为点(i,j)存储对于id: i*m+j)走过来的。当遍历到(n,m)时,可以得到一条最短路径。然后从(n,m)倒序恢复整条路径。

import java.util.*;
public class Main {
    static int[] dx, dy;
    static int[][] bfs(int[][] grid, int n, int m) {
        //id : x*m + y
        int[][] ans = new int[n][m];
        Queue<Integer> q = new LinkedList<>();
        q.offer(0);
        while(!q.isEmpty()) {
                int cur = q.poll();
                int x = cur / m, y = cur % m;
                //System.out.println(x+","+y);
                for(int j=0; j < 4; j++) {
                    int xx = dx[j] + x, yy = dy[j] + y;
                    if(xx>= 0 && xx<n && yy >=0 && yy < m && grid[xx][yy] == 0) {
                        grid[xx][yy] = 2;
                        q.offer(xx*m+yy);
                        ans[xx][yy] = cur;
                    }
                }
        }
        //System.out.println(Arrays.deepToString(ans));
        return ans;
    }
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        dx = new int[] {0, 1, 0, -1};
        dy = new int[] {1, 0, -1, 0};
        while(sc.hasNext()){
            int n =sc.nextInt(), m = sc.nextInt();
            int[][] grid = new int[n][m];
            for(int i=0; i < n; i++)
                for(int j=0; j < m; j++)
                    grid[i][j] = sc.nextInt();
            int[][] path = bfs(grid, n, m);
            List<int[]> res = new ArrayList<>();
            res.add(new int[] {n-1, m-1});
            int x = n-1, y = m-1;
            while(!(x == 0 && y == 0)) {
                int t = path[x][y];
                x = t / m; y = t % m;
                res.add(new int[] {x, y});
            }
            for(int i=res.size()-1; i >= 0; i--) {
                System.out.println("(" + res.get(i)[0] +"," + res.get(i)[1]+")");
            }
        }
    }
}
原文地址:https://www.cnblogs.com/lixyuan/p/13272968.html