栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现走迷宫问题

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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 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;
    }
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1006769.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号