方格迷宫 BFS 剪枝

AcWing 4943. 方格迷宫
在这里插入图片描述
在这里插入图片描述
输入样例1

3 4 4
....
###.
....
1 1 3 1

输出样例1

3

输入样例2

3 4 1
....
###.
....
1 1 3 1

输出样例2

8

输入样例3

2 2 1
.#
#.
1 1 2 2

输出样例3

-1

⭐ 思路
① 先暴力BFS
② 剪枝:只要 t点+1 的距离 < x点了,那就没必要用 t 点去更新 x 点的距离了

import java.util.Arrays;
import java.util.LinkedList;
import java.util.Scanner;

public class Main
{
    
    
	static int n, m, k;
	static int N = 1010;
	static char[][] g = new char[N][N];
	static int[][] dist = new int[N][N];

	static int[] dx = {
    
     0, 1, 0, -1 };
	static int[] dy = {
    
     1, 0, -1, 0 };

	public static void main(String[] args)
	{
    
    
		Scanner sc = new Scanner(System.in);
		n = sc.nextInt();
		m = sc.nextInt();
		k = sc.nextInt();

		for (int i = 1; i <= n; i++)
		{
    
    
			String s = sc.next();
			for (int j = 1; j <= m; j++)
				g[i][j] = s.charAt(j - 1);
		}
		int x1 = sc.nextInt();
		int y1 = sc.nextInt();
		Node st = new Node(x1, y1);

		int x2 = sc.nextInt();
		int y2 = sc.nextInt();
		Node end = new Node(x2, y2);

		int res = bfs(st, end);
		System.out.println(res);

	}

	private static int bfs(Node st, Node end)
	{
    
    
		if (st.x == end.x && end.y == st.y)
		{
    
    
			return 0;
		}

		LinkedList<Node> q = new LinkedList<>();
		for (int i = 0; i < dist.length; i++)
		{
    
    
			Arrays.fill(dist[i], 0x3f3f3f3f);
		}

		q.add(st);
		dist[st.x][st.y] = 0;
		while (!q.isEmpty())
		{
    
    
			Node t = q.pop();
			for (int i = 0; i < 4; i++)
				for (int j = 1; j <= k; j++)
				{
    
    
					int x = t.x + j * dx[i];
					int y = t.y + j * dy[i];
					if (x < 1 || x > n || y < 1 || y > m || g[x][y] == '#')
						break;
				// 	只要d(x,y) 的距离 小于 d[t.x,t.y] 的距离时,就没必要用 t 去更新 点(x,y) 的距离了 
					if(dist[x][y] <= dist[t.x][t.y])
                        break;					    

					if (dist[x][y] > dist[t.x][t.y] + 1)
					{
    
    
						dist[x][y] = dist[t.x][t.y] + 1;
//						更新后就可以判断终点返回了
						if (x == end.x && y == end.y)
							return dist[x][y];

						q.add(new Node(x, y));
					}
				}
		}
		return -1;
	}

	static class Node
	{
    
    

		int x;
		int y;

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

猜你喜欢

转载自blog.csdn.net/lt6666678/article/details/129931395