AcWing 1101. 献给阿尔吉侬的花束java
原题链接
简单
作者:
nq
,
2021-03-13 18:34:09
,
所有人可见
,
阅读 478
import java.util.*;
import java.io.*;
public class Main{
static final int N = 200;
static int T ,R , C;
static char[][] g = new char[N][N];
static int[][] dist = new int[N][N];
static BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
private static int bfs(int[] s , int[] e)
{
Queue<int[]>q = new LinkedList<>();
for(int i = 0 ; i < R ; i ++) {
Arrays.fill(dist[i], -1);
}
dist[s[0]][s[1]] = 0;
q.offer(s);
while(!q.isEmpty())
{
int[] tmp = q.poll();
int dx[] = {0,0,-1,1} , dy[] = {1,-1,0,0};
for(int i = 0 ; i < 4 ; i ++)
{
int x = tmp[0]+dx[i] , y = tmp[1]+dy[i];
if(x < 0 || x >= R || y < 0 || y >= C || dist[x][y] != -1 || g[x][y] == '#')
{
continue;
}
dist[x][y] = dist[tmp[0]][tmp[1]] + 1;
if(e[0] == x && e[1] == y) return dist[x][y];
q.offer(new int[] {x , y});
}
}
return -1;
}
public static void main(String[] args) throws IOException
{
int[] s = new int[2], e = new int[2];
T = Integer.parseInt(in.readLine());
while(T -- > 0)
{
String[] read = in.readLine().split(" ");
R = Integer.parseInt(read[0]);
C = Integer.parseInt(read[1]);
for(int i = 0 ; i < R ; i ++) {
g[i] = in.readLine().toCharArray();
}
for (int i = 0 ; i < R ; i ++)
{
for (int j = 0 ; j < C ; j ++)
{
if(g[i][j] == 'S')s = new int[] {i,j};
else if(g[i][j] == 'E')e = new int[] {i,j};
}
}
int dis = bfs(s , e);
if(dis == -1)System.out.println("oop!");
else System.out.println(dis);
}
}
}