编辑代码

import java.util.Scanner;

public class Main {
    private static final int[] dx = {0, 1, 0, -1}; // x轴方向移动
    private static final int[] dy = {1, 0, -1, 0}; // y轴方向移动
    private static int minProtection = Integer.MAX_VALUE;
    private static int[][] maze;
    private static boolean[][] visited;
    private static int n, k;

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        k = scanner.nextInt();
        maze = new int[n][n];
        visited = new boolean[n][n];

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                maze[i][j] = scanner.nextInt();
            }
        }
        scanner.close();

        dfs(0, 0, 0, maze[0][0]);
        System.out.println(minProtection);
    }

    private static void dfs(int x, int y, int steps, int maxRadiation) {
        if (x < 0 || x >= n || y < 0 || y >= n || visited[x][y]) {
            return;
        }

        maxRadiation = Math.max(maxRadiation, maze[x][y]);
        if (x == n - 1 && y == n - 1) {
            if (steps <= k) {
                minProtection = Math.min(minProtection, maxRadiation);
            }
            return;
        }

        visited[x][y] = true;
        for (int i = 0; i < 4; i++) {
            int newX = x + dx[i];
            int newY = y + dy[i];
            if (steps + 1 <= k) {
                dfs(newX, newY, steps + 1, maxRadiation);
            }
        }
        visited[x][y] = false;
    }
}