BaekJoon
17144번:미세먼지 안녕![Java]
충 민
2022. 8. 30. 23:34
문제에 대한 이해가 조금 어려울 수도 있다.
미세먼지의 확산이 동시에 된다는 것을 생각하고 문제를 읽는다면 이해가 빠를 것이다.
특별한 알고리즘 없이 반복문으로 구현한 것이다.
코드는 아래와 같다.
package algorithm17144;
import java.util.*;
public class Main {
public static void main(String[] ags) {
var sc = new Scanner(System.in); //자동형변환
int R, C, T;//행 열 초
R = sc.nextInt();
C = sc.nextInt();
T = sc.nextInt();
//현재 미세먼지를 담을 배열
int[][] cur = new int[C][R];
//확산 후 미세먼지를 담을 배열
int[][] next = new int[C][R];
//상하좌우
int[] dx = { 0, 0, 1, -1 };
int[] dy = { 1, -1, 0, 0 };
int dust = 0;
int[] y = new int[2];
boolean check = true;
//미세먼지를 담는 반복문
for (int i = 0; i < R; i++) {
for (int j = 0; j < C; j++) {
int a = sc.nextInt();
cur[j][i] = a;
if (a != -1 && a != 0) {
dust += a;
}
if (a == -1 && check) {
y[0] = i;
y[1] = i + 1;
check = false;
}
}
}
//확산된 미세먼지를 담는 반복문
for (int i = 0; i < T; i++) {
next = new int[C][R];
for (int j = 0; j < R; j++) {
for (int k = 0; k < C; k++) {
if (cur[k][j] > 0) {
int d = cur[k][j] / 5;
for (int c = 0; c < 4; c++) {
int nx = k + dx[c];
int ny = j + dy[c];
if (nx >= 0 && ny >= 0 && nx < C && ny < R) {
if (!(nx == 0 && (ny == y[0] || ny == y[1]))) {
next[nx][ny] += d;
cur[k][j] -= d;
}
}
}
next[k][j] += cur[k][j];
}
}
}
dust -= (next[0][y[0] - 1] + next[0][y[1] + 1]);
//바람이 불면 미세먼지가 바람의 방향대로 모두 한칸씩이동
for (int j = y[0] - 2; j >= 0; j--) {
next[0][j + 1] = next[0][j];
}
for (int j = 1; j < C; j++) {
next[j - 1][0] = next[j][0];
}
for (int j = 1; j <= y[0]; j++) {
next[C - 1][j - 1] = next[C - 1][j];
}
for (int j = C - 1; j > 1; j--) {
next[j][y[0]] = next[j - 1][y[0]];
}
next[1][y[0]] = 0;
for (int j = y[1] + 2; j < R; j++) {
next[0][j - 1] = next[0][j];
}
for (int j = 1; j < C; j++) {
next[j - 1][R - 1] = next[j][R - 1];
}
for (int j = R - 1; j >= y[1]; j--) {
next[C - 1][j] = next[C - 1][j-1];
}
for (int j = C - 1; j > 1; j--) {
next[j][y[1]] = next[j - 1][y[1]];
}
next[1][y[1]] = 0;
cur = next;
}
System.out.print(dust);
}
}