迷宫最短路径|BFS模板

迷宫

/*
 * n=10 m=10
	#S######.#
	......#..#
	.#.##.##.#
	.#........
	##.##.####
	....#....#
	.#######.#
	....#.....
	.####.###.
	....#...G#
 */
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class 迷宫问题 {

	static int n;
	static int m;
	static int[] dx = { 1, 0, -1, 0 };
	static int[] dy = { 0, 1, 0, -1 };
	static char[][] maze;

	public static class Node {
		public int x;
		public int y;

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

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		m = sc.nextInt();
		sc.nextLine();
		maze = new char[n][m];
		for (int i = 0; i < maze.length; i++) {
			maze[i] = sc.nextLine().toCharArray();
		}
		int ans = bfs();
		System.out.println(ans);
	}

	private static int bfs() {
		int sx = 0, sy = 1, gx = n - 1, gy = m - 2;
		int[][] d = new int[n][m];
		// -1表示改点没有访问过
		for (int i = 0; i < n; i++) {
			for (int j = 0; j < m; j++) {
				d[i][j] = -1;
			}
		}
		// 新建队列,将起点入队并登记距离
		Queue<Node> que = new LinkedList<>();
		Node firstNode = new Node(sx, sy);
		que.add(firstNode);
		d[sx][sy] = 0;

		while (!que.isEmpty()) {
			// 取出
			Node curNode = que.poll();
			int cx = curNode.x;
			int cy = curNode.y;
			if (cx == gx && cy == gy) {
				return d[gx][gy];
			}

			// 访问其他临近并且可以访问的节点
			for (int i = 0; i < 4; i++) {
				int nx = cx + dx[i];
				int ny = cy + dy[i];
				// 判断是否访问过,越界,可行
				if ((0 <= nx && nx < n) && (0 <= ny && ny < m) && (d[nx][ny] == -1) && (maze[nx][ny] != '#')) {
					Node nextNode = new Node(nx, ny);
					que.add(nextNode);
					d[nx][ny] = d[cx][cy] + 1;
				}
			}
		}
		return d[gx][gy];
	}
}

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值