3 条题解
-
0
java题解:
import java.util.*; import java.io.*; public class Main { static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); static StringTokenizer st; public static void main(String[] args) throws IOException { solve(); } static void solve() throws IOException { st = new StringTokenizer(br.readLine()); int n = Integer.parseInt(st.nextToken()); int m = Integer.parseInt(st.nextToken()); char[][] grid = new char[n][m]; int sx = -1, sy = -1; // 读取网格 for (int i = 0; i < n; i++) { String line = br.readLine(); grid[i] = line.toCharArray(); if (sx == -1) { for (int j = 0; j < m; j++) { if (grid[i][j] == 'S') { sx = i; sy = j; break; } } } } if (sx == -1) { System.out.println(-1); return; } int[] dx = {-1, 0, 1, 0}; int[] dy = {0, 1, 0, -1}; // 使用Set记录访问状态,避免三维数组 Set<Integer> visited = new HashSet<>(); Queue<int[]> q = new LinkedList<>(); // 状态编码: (x << 20) | (y << 10) | can int startState = encode(sx, sy, 1); visited.add(startState); q.offer(new int[]{sx, sy, 1, 0}); // {x, y, can, dist} while (!q.isEmpty()) { int[] cur = q.poll(); int x = cur[0]; int y = cur[1]; int can = cur[2]; int dist = cur[3]; if (grid[x][y] == 'E') { System.out.println(dist); return; } // 正常移动 for (int d = 0; d < 4; d++) { int nx = x + dx[d]; int ny = y + dy[d]; int ncan = 1; if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] != '#') { int state = encode(nx, ny, ncan); if (!visited.contains(state)) { visited.add(state); q.offer(new int[]{nx, ny, ncan, dist + 1}); } } } // 跳跃移动 if (can == 1) { for (int d = 0; d < 4; d++) { int nx = x + dx[d] * 2; int ny = y + dy[d] * 2; int ncan = 0; if (nx >= 0 && nx < n && ny >= 0 && ny < m && grid[nx][ny] != '#') { int state = encode(nx, ny, ncan); if (!visited.contains(state)) { visited.add(state); q.offer(new int[]{nx, ny, ncan, dist + 1}); } } } } } System.out.println(-1); } static int encode(int x, int y, int can) { // 假设n,m≤1000,x和y各用10位足够 return (x << 20) | (y << 10) | can; } }
信息
- ID
- 5629
- 时间
- 1000ms
- 内存
- 256MiB
- 难度
- 9
- 标签
- 递交数
- 27
- 已通过
- 4
- 上传者