AcWing 1101. 献给阿尔吉侬的花束 宽搜 边界处理 java
原题地址


输入样例
3
3 4
.S..
###.
..E.
3 4
.S..
.E..
....
3 4
.S..
####
..E.
输出样例
5
1
oop!
⭐ 从起点开始,暴力BFS,用队列实现,走过的地方改成 墙 避免走老路
🤬 细节输出:使用 buffer 流输出记得手动打 换行符
package algorithm.lanQiao.宽搜;
import java.io.*;
import java.net.Inet4Address;
import java.util.*;
public class 献给阿尔吉侬的花束
{
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
static BufferedWriter out = new BufferedWriter(new OutputStreamWriter(System.out));
static int N = 210;
static char[][] arr = 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 };
static class Pair
{
int x;// 存横坐标
int y;// 存纵坐标
public Pair(int x, int y)
{
super();
this.x = x;
this.y = y;
}
}
public static void main(String[] args) throws IOException
{
int T = Integer.parseInt(in.readLine());
while (T-- > 0)
{
String[] ss = in.readLine().split(" ");
int r = Integer.parseInt(ss[0]);
int c = Integer.parseInt(ss[1]);
// 初始化地图(整个地图都是墙)(宽搜的时候就不用特殊处理边界的问题了)
for (int i = 0; i < N; i++)
{
Arrays.fill(arr[i], '#');
}
// 初始化距离
for (int i = 0; i < dist.length; i++)
{
Arrays.fill(dist[i], 0);
}
Pair start = null, end = null;// 用 Pair 记录起终点
// 输入
for (int i = 1; i <= r; i++)
{
String s = in.readLine();
for (int j = 1; j <= c; j++)
{
arr[i][j] = s.charAt(j - 1);
// 顺便记录起点和终点
if (arr[i][j] == 'S')
start = new Pair(i, j);
if (arr[i][j] == 'E')
end = new Pair(i, j);
}
}
int res = bfs(start, end);
if (res == -1)
out.write("oop!\n");
else
{
out.write(res + "\n");
}
}
out.flush();
}
private static int bfs(Pair start, Pair end)
{
LinkedList<Pair> q = new LinkedList<>();
q.add(start);
while (!q.isEmpty())
{
Pair t = q.poll();
int x = t.x;
int y = t.y;
for (int i = 0; i < 4; i++)
{
int xx = x + dx[i];
int yy = y + dy[i];
if (arr[xx][yy] == '#')
continue;
dist[xx][yy] = dist[x][y] + 1;
if (arr[xx][yy] == 'E')
return dist[xx][yy];
arr[xx][yy] = '#';// 遍历过的地方改为墙,实现间接去重
q.add(new Pair(xx, yy));
}
}
return -1;
}
}

浙公网安备 33010602011771号