题目描述:
阿尔吉侬是一只聪明又慵懒的小白鼠,它最擅长的就是走各种各样的迷宫。
今天它要挑战一个非常大的迷宫,研究员们为了鼓励阿尔吉侬尽快到达终点,就在终点放了一块阿尔吉侬最喜欢的奶酪。
现在研究员们想知道,如果阿尔吉侬足够聪明,它最少需要多少时间就能吃到奶酪。 迷宫用一个 R×C的字符矩阵来表示。 字符 S
表示阿尔吉侬所在的位置,字符 E 表示奶酪所在的位置,字符 # 表示墙壁,字符 . 表示可以通行。 阿尔吉侬在 1
个单位时间内可以从当前的位置走到它上下左右四个方向上的任意一个位置,但不能走出地图边界。输入格式:
第一行是一个正整数 T,表示一共有 T 组数据。 每一组数据的第一行包含了两个用空格分开的正整数 R 和 C,表示地图是一个 R×C的矩阵。
接下来的 R 行描述了地图的具体内容,每一行包含了 C 个字符。字符含义如题目描述中所述。保证有且仅有一个 S 和 E。输出格式:
对于每一组数据,输出阿尔吉侬吃到奶酪的最少单位时间。 若阿尔吉侬无法吃到奶酪,则输出“oop!”(只输出引号里面的内容,不输出引号)。
每组数据的输出结果占一行。数据范围:
1<T≤10,
2≤R,C≤200
输入样例:
3
3 4
.S…
###.
…E.
3 4
.S…
.E…
…
3 4
.S…
…E.
输出样例:
5
1
oop!
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[] dx = {-1, 0, 1, 0};
static int[] dy = {0, 1, 0, -1};
static int row;
static int col;
static char[][] arr;
static int[][] visited;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
while(count-- > 0) {
row = sc.nextInt();
col = sc.nextInt();
arr = new char[row][col];
visited = new int[row][col];
for(int i = 0; i < row; i++) {
String str = sc.next();
arr[i] = str.toCharArray();
}
int[] st = new int[2];
int[] ed = new int[2];
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(arr[i][j] == 'S') {
st = new int[]{i, j};
}
}
}
System.out.println(bfs(st));
}
}
public static String bfs(int[] st) {
Queue<int[]> queue = new LinkedList<>();
queue.add(new int[]{st[0], st[1]});
arr[st[0]][st[1]] = '#';
while(!queue.isEmpty()) {
int[] cur = queue.poll();
int x = cur[0];
int y = cur[1];
for(int d = 0; d < 4; d++) {
int x1 = x + dx[d];
int y1 = y + dy[d];
if(x1 < 0 || y1 < 0 || x1 >= row || y1 >= col ||arr[x1][y1] == '#' ) {
continue;
}
if(arr[x1][y1] == 'E') {
return visited[x][y] + 1 + "";
}
visited[x1][y1] = visited[x][y] + 1;
arr[x1][y1] = '#';
queue.add(new int[]{x1, y1});
}
}
return "oop!";
}
}