import java.util.*; public class Main { public static int n, m; public static boolean ok(int x, int y) { return x >= 0 && x < n && y >= 0 && y < m; } public static void main(String[] args) { Scanner sc = new Scanner(System.in); int T = sc.nextInt(); for(int id = 1; id <= T; id++) { int sx, sy, tx = 0, ty = 0; n = sc.nextInt(); m = sc.nextInt(); sx = sc.nextInt() - 1; sy = sc.nextInt() - 1; char[][] g = new char[n][]; int[][][] dis = new int[n][m][2]; for(int i = 0; i < n; i++) { g[i] = sc.next().toCharArray(); for(int j = 0; j < m; j++) { if(g[i][j] == 'E') { g[i][j] = '_'; tx = i; ty = j; } dis[i][j][0] = -1; dis[i][j][1] = -1; } } Queue<int[]> q = new LinkedList<>(); q.add(new int[]{sx, sy, 0}); dis[sx][sy][0] = 0; int[] dx = {0, 0, 1, -1}; int[] dy = {1, -1, 0, 0}; while(!q.isEmpty()) { int x = q.peek()[0]; int y = q.peek()[1]; int z = q.peek()[2]; q.poll(); for(int i = 0; i < 4; i++) { int nx = x + dx[i], ny = y + dy[i]; if(!ok(nx, ny)) continue; if(g[nx][ny] == '_') { if(dis[nx][ny][z] == -1) { dis[nx][ny][z] = dis[x][y][z] + 1; q.add(new int[]{nx, ny, z}); } } else if(z == 0) { while(ok(nx, ny) && g[nx][ny] == 'X') { if(dis[nx][ny][1] == -1) { dis[nx][ny][1] = dis[x][y][0] + 1; q.add(new int[]{nx, ny, 1}); } nx += dx[i]; ny += dy[i]; } } } } int ans = -1; if(dis[tx][ty][0] != -1) ans = dis[tx][ty][0]; if(dis[tx][ty][1] != -1 && (ans == -1 || ans > dis[tx][ty][1])) ans = dis[tx][ty][1]; System.out.println("#" + id + " " + ans); } } }
时间: 2023-06-05 15:08:44 浏览: 124
java代码-import java.util.Scanner;
该代码段是Java语言的代码,定义了一个名为Main的公共类,其中包括一个名为n、m的静态int变量和一个名为ok的静态boolean函数。此外,该代码还导入了Java的util库。函数ok的功能是判断一个x和y是否符合条件,当且仅当x大于等于0且y大于等于0时,返回值为true,否则为false。
阅读全文