java实现走迷宫问题

题目链接:https://www.nowcoder.com/questionTerminal/6276dbbda7094978b0e9ebb183ba37b9
在这里插入图片描述

bfs:

import java.util.*;

class Node {
    int x;
    int y;
    int count;

    public Node(int x, int y, int count) {
        this.x = x;
        this.y = y;
        this.count = count;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String[] strings = new String[10];
            for (int i = 0; i < 10; i++) {
                strings[i] = sc.nextLine();
            }
            System.out.println(bfs(strings,10,10));
        }
    }
    public static int bfs(String[] strings,int m,int n) {
        //四个方向
        int[][] direct = {{1,0},{0,1},{0,-1},{-1,0}};
        //初始节点
        Node start = new Node(0,1,0);
        //结束节点
        Node end = new Node(9,8,0);
        //判断是否走过
        boolean[][] flag = new boolean[m][n];


        Queue<Node> queue = new LinkedList<>();
        queue.offer(start);

        while (!queue.isEmpty()) {
            Node node = queue.poll();
            flag[node.x][node.y] = true;

            //到达终点
            if (node.x == end.x && node.y == end.y) {
                return node.count;
            }

            for (int i = 0; i < 4; i++) {
                Node next = new Node(node.x+direct[i][0],node.y+direct[i][1],node.count+1);

                if (next.x >= 0 && next.x < m && next.y >= 0 && next.y < n
                        && strings[next.x].charAt(next.y) == '.'&& !flag[next.x][next.y]) {
                    queue.add(next);
                }
            }
        }
        return 0;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值