Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
1.6 kB
2
Indexable
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int T = sc.nextInt(); // Số lượng trường hợp
        for (int t = 0; t < T; t++) {
            int N = sc.nextInt(); // Số hàng
            int M = sc.nextInt(); // Số cột
            int[][] city = new int[N][M];

            // Đọc trạng thái ban đầu của thành phố
            for (int i = 0; i < N; i++) {
                for (int j = 0; j < M; j++) {
                    city[i][j] = sc.nextInt();
                }
            }

            int bomb_x = sc.nextInt(); // Vị trí x của bom
            int bomb_y = sc.nextInt(); // Vị trí y của bom

            int time = spreadContamination(city, bomb_x, bomb_y, N, M);
            System.out.println(time);
        }
        sc.close();
    }

    public static int spreadContamination(int[][] city, int bomb_x, int bomb_y, int N, int M) {
        if (city[bomb_x][bomb_y] == 1) {
            return 0;
        }

        int[][] directions = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        int time = 0;

        for (int[] dir : directions) {
            int new_x = bomb_x + dir[0];
            int new_y = bomb_y + dir[1];

            if (new_x >= 0 && new_x < N && new_y >= 0 && new_y < M && city[new_x][new_y] == 1) {
                city[new_x][new_y] = 2;
                int subTime = spreadContamination(city, new_x, new_y, N, M);
                if (subTime > time) {
                    time = subTime;
                }
            }
        }

        return time + 1;
    }
}