方格迷宫 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;
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 地球OL攻略 —— 某应届生求职总结
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 提示词工程——AI应用必不可少的技术
· .NET周刊【3月第1期 2025-03-02】