华为OJ 走迷宫 Java BFS

26 篇文章 1 订阅
class Node{
int x;
int y;
int prex; //上一个结点的坐标,为方便计算路径
int prey; 
}
public class Maze{
    public static void main(String args){
    Scanner sc = new Scanner(System.in);
    while(sc.hasNext()){
        //读入数据
        int m = sc.nextInt();
        int n = sc.nextInt();
        int[][] map = new int[m][n];
        for(int i = 0; i < m; i++){
            for(int j = 0; j < n; j++){
                map[i][j] = sc.nextInt();
            }
        }

        //为BFS做些初始化
        Queue<Node> queue = new LinkedList<Node>();
        ArrayList<Node> arrayList = new ArrayList<Node>();
        int[][] visited = new int[m][n];
        int[][] dir = {{1,0},{0,1}};

        //起始点为(0,0),终点为(m-1,n-1),即从左上走到右下,所以dir只有2个方向
        queue.offer(new Node(0,0)); 
        visited[0][0] = 1;
        while(!queue.isEmpty()){
            Node local = queue.remove();
            arrayList.add(local);
            for(int i=0; i< dir.length; i++){
                Node next = new Node(local.x+dir[i][0], local.y+dir[i][1]);
                if(next.x>=0 && next.x < m 
                && next.y >= 0 && next.y < n 
                && map[next.x][next.y]==0){
                    queue.offer(next);
                    visited[next.x][next.y] = 1;
                    next.prex = local.x;
                    next.prey = local.y;
                }
            }

            //接下来就是输出路径了
            Stack<Integer> stack = new Stack<Integer>();
            //出口的上一个结点
            int px = arrayList.get(arrayList.size()-1).prex;
            int py = arrayList.get(arrayList.size()-1).prey;
            while(true){
                if(px == 0 && py == 0){
                    break;
                }
                for(int i = 0; i < arrayList.size(); i++){
                    if(arrayList.get(i).prex==px && arrayList.get(i).prey==py){
                        px = arrayList.get(i).prex;
                        py = arrayList.get(i).prey;
                        stack.push(i);
                        break;
                    }
                }
            }
            stack.push(0);
            while(!stack.isEmpty()){
                System.out.println("("+arrayList.get(stack.peer()).x+","+arrayList.get(stack.peer()).y+")");
                stack.pop();
            }
        }
    }
    sc.close();
    }
}
输入例子:
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0

输出例子:
(0,0)
(1,0)
(2,0)
(2,1)
(2,2)
(2,3)
(2,4)
(3,4)
(4,4)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值