미세먼지 안녕!

Updated:

import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main {

	static int R;
	static int C;

	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Scanner sc = new Scanner(System.in);

		R = sc.nextInt();
		C = sc.nextInt();

		int T = sc.nextInt();
		int[][] arr = new int[R][C];
		for (int i = 0; i < R; i++) {
			for (int j = 0; j < C; j++) {
				arr[i][j] = sc.nextInt();

			}
		}
		Queue<Node> q = new LinkedList<>();

		for (int k = 0; k < T; k++) {
			for (int i = 0; i < R; i++) {
				for (int j = 0; j < C; j++) {
					if (arr[i][j] > 4) {
						q.add(new Node(i, j, arr[i][j]));
						arr[i][j] = 0;
					}

				}

			}

			while (!q.isEmpty()) {
				Node node = q.poll();
				int cnt = 0;
				for (int j = 0; j < 4; j++) {
					int nr = node.r + dr[j];
					int nc = node.c + dc[j];
					if (nr >= 0 && nr < R && nc >= 0 && nc < C) {
						if (arr[nr][nc] != -1) {
							cnt++;
							arr[nr][nc] += node.val / 5;
						}
					}
				}
				arr[node.r][node.c] += node.val - cnt * (node.val / 5);
			}
			boolean che = false;
			int x = 0;
			for (int i = 0; i < R; i++) {
				int y = i;
				if (arr[y][x] == -1) {

					while (x == 0 && y - 2 >= 0) {
						y--;
						arr[y][x] = arr[y - 1][x];
					}
					y--;

					while (y == 0 && x + 1 < C) {
						arr[y][x] = arr[y][x + 1];
						x++;
					}

					while (x == C - 1 && y + 1 < i + 1) {
						arr[y][x] = arr[y + 1][x];
						y++;
					}

					while (y == i && x - 1 >= 1) {
						arr[y][x] = arr[y][x - 1];
						x--;
					}
					arr[y][x] = 0;
					i = i + 1;
					y = i;
					x = 0;

					while (x == 0 && y + 2 < R) {
						y++;
						arr[y][x] = arr[y + 1][x];
					}
					y++;

					while (y == R - 1 && x + 1 < C) {
						arr[y][x] = arr[y][x + 1];
						x++;
					}

					while (x == C - 1 && y - 1 >= i) {
						arr[y][x] = arr[y - 1][x];
						y--;
					}

					while (y == i && x - 1 >= 1) {
						arr[y][x] = arr[y][x - 1];
						x--;
					}
					arr[y][x] = 0;
				}

			}

		}
		int sum = 0;
		for (int i = 0; i < R; i++) {
			for (int j = 0; j < C; j++) {
				sum += arr[i][j];
			}
		}
		System.out.println(sum + 2);

	}

	static int[] dr = { -1, 1, 0, 0 };
	static int[] dc = { 0, 0, -1, 1 };

	static class Node {
		int r, c, val;

		Node(int r, int c, int val) {
			this.r = r;
			this.c = c;
			this.val = val;
		}
	}

}

Leave a comment