|
| 1 | +package Simulation.P2636; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class Main { |
| 7 | + |
| 8 | + static int R, C, total; |
| 9 | + static int[][] map; |
| 10 | + static int[] di = {-1, 0, 1, 0}; |
| 11 | + static int[] dj = {0, 1, 0, -1}; |
| 12 | + |
| 13 | + public static void main(String[] args) throws Exception { |
| 14 | + System.setIn(new FileInputStream("src/Simulation/P2636/input.txt")); |
| 15 | + BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); |
| 16 | + StringTokenizer st = new StringTokenizer(br.readLine()); |
| 17 | + |
| 18 | + R = Integer.parseInt(st.nextToken()); |
| 19 | + C = Integer.parseInt(st.nextToken()); |
| 20 | + |
| 21 | + map = new int[R][C]; |
| 22 | + for (int i = 0; i < R; i++) { |
| 23 | + st = new StringTokenizer(br.readLine()); |
| 24 | + for (int j = 0; j < C; j++) { |
| 25 | + map[i][j] = Integer.parseInt(st.nextToken()); |
| 26 | + if (map[i][j] == 1) total ++; |
| 27 | + } |
| 28 | + } |
| 29 | + |
| 30 | + solve(); |
| 31 | + } |
| 32 | + |
| 33 | + static void solve() { |
| 34 | + Queue<Pos> air = new LinkedList<>(); |
| 35 | + Queue<Pos> cheese = new LinkedList<>(); |
| 36 | + boolean[][] visited = new boolean[R][C]; |
| 37 | + int time = 0; |
| 38 | + |
| 39 | + air.add(new Pos(0, 0)); |
| 40 | + while (total > 0) { |
| 41 | + time ++; |
| 42 | + |
| 43 | + while (!air.isEmpty()) { |
| 44 | + Pos p = air.poll(); |
| 45 | + visited[p.i][p.j] = true; |
| 46 | + |
| 47 | + for (int k = 0; k < 4; k++) { |
| 48 | + int to_i = p.i + di[k]; |
| 49 | + int to_j = p.j + dj[k]; |
| 50 | + |
| 51 | + if (!isValidPath(to_i, to_j) || visited[to_i][to_j]) continue; |
| 52 | + |
| 53 | + visited[to_i][to_j] = true; |
| 54 | + if (map[to_i][to_j] == 0) { |
| 55 | + air.offer(new Pos(to_i, to_j)); |
| 56 | + } else { |
| 57 | + cheese.offer(new Pos(to_i, to_j)); |
| 58 | + total --; |
| 59 | + } |
| 60 | + } |
| 61 | + } |
| 62 | + |
| 63 | + air.addAll(cheese); |
| 64 | + cheese.clear(); |
| 65 | + } |
| 66 | + |
| 67 | + System.out.println(time); |
| 68 | + System.out.println(air.size()); |
| 69 | + } |
| 70 | + |
| 71 | + static boolean isValidPath(int i, int j) { |
| 72 | + return 0 <= i && i < R && 0 <= j && j < C; |
| 73 | + } |
| 74 | + |
| 75 | + static class Pos { |
| 76 | + int i, j; |
| 77 | + |
| 78 | + public Pos(int i, int j) { |
| 79 | + this.i = i; |
| 80 | + this.j = j; |
| 81 | + } |
| 82 | + } |
| 83 | +} |
0 commit comments