走迷宫..

链接:https://www.nowcoder.com/questionTerminal/6276dbbda7094978b0e9ebb183ba37b9
来源:牛客网

NowCoder最喜欢游乐场的迷宫游戏,他和小伙伴们比赛谁先走出迷宫。
现在把迷宫的地图给你,你能帮他算出最快走出迷宫需要多少步吗?

输入描述:

输入包含多组数据。

每组数据包含一个10*10,由“#”和“.”组成的迷宫。其中“#”代表墙;“.”代表通路。

入口在第一行第二列;出口在最后一行第九列。

从任意一个“.”点都能一步走到上下左右四个方向的“.”点。

输出描述:

对应每组数据,输出从入口到出口最短需要几步。

示例1
输入

#.########
#........#
#........#
#........#
#........#
#........#
#........#
#........#
#........#
########.#
#.########
#........#
########.#
#........#
#.########
#........#
########.#
#........#
#.######.#
########.#

输出

16
30
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Maze {
    static class Point {
        int x;
        int y;
        int step;
        public Point(int x, int y, int step) {
            this.x = x;
            this.y = y;
            this.step = step;
        }
    }
    static int[][] next = {{1,0},{-1,0},{0,1},{0,-1}};
    public static void main(String[] args) {
        int n =10;
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            String[] arr = new String[n];
            for (int i = 0; i < n; i++) {
                arr[i] = scanner.nextLine();
            }
            char[][] maze = new char[n][n];
            for (int i = 0; i <n; i++) {
                for (int j = 0; j < n; j++) {
                    maze[i][j] = arr[i].charAt(j);
                }
            }
            System.out.println(bfs(maze, 0, 1));
        }
    }

    private static int bfs(char[][] maze, int x, int y) {
        Queue<Point> que = new LinkedList<>();
        que.add(new Point(x,y,0));
        int[][] visit = new int[10][10];
        while (!que.isEmpty()) {
            Point cur = que.poll();
            if (cur.x == 9 && cur.y == 8) {
                return cur.step;
            }
            // 搜索4个方向
            for (int i = 0; i < 4; i++) {
                int nx = cur.x + next[i][0];
                int ny = cur.y + next[i][1];
                if (nx < 0 || nx >= 10 || ny<0 || ny >=10) {
                    continue;
                }
                // 没有障碍且没有访问过
                if (maze[nx][ny] == '.' && visit[nx][ny]== 0) {
                    que.add(new Point(nx,ny,cur.step+1));
                    visit[nx][ny] = 1;
                }
            }
        }
        return 0;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值