
https://www.acmicpc.net/status?user_id=chabin37&problem_id=1022&from_mine=1
문제분석
구현의 악마.
소용돌이가 내 머릿속에서 도는걸 느낄 수 있는 문제다.
이 문제의 가장 핵심은, 규칙을 찾는 것이다(당연함).
사람들이 다양한 규칙을 사용하는 것 같지만, 나는 이렇게 사용했다.

좌하단-우상단 가로지르는 대각선 친구들을 보면, 다음과 같은 점화식(오른쪽 식) 을 구할 수 있다. 따라서 주어진 좌표의 값을 얻고 싶으면,
1. 해당 좌표와 연관된 기준점(점화식으로 구할 수 있는 점들)을 먼저 구하고
2. 그 기준점과 좌표가 어떻게 연관되어 있는지(x축/y축) 인지 파악한 뒤
계산하면 된다.
+ 추가로, 예쁘게 출력해야 하기 때문에, printf("%"+width+"d"+" ", 값) 이라는 방식으로 열을 맞춰야 한다.(최소 width 확보 라는 기능...)
코드
import java.io.*;
import java.util.*;
public class Main{
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String input = br.readLine();
String[] inputs = input.split(" ");
int r1 = Integer.parseInt(inputs[0]);
int c1 = Integer.parseInt(inputs[1]);
int r2 = Integer.parseInt(inputs[2]);
int c2 = Integer.parseInt(inputs[3]);
int[][] result = new int[r2 - r1 + 1][c2 - c1 + 1];
int max = Integer.MIN_VALUE;
for(int i = 0; i < r2 - r1 + 1; i++){
for(int j = 0; j < c2 - c1 + 1; j++){
result[i][j] = getInt(r1 + i, c1 + j);
max = Math.max(max, result[i][j]);
}
}
int width = String.valueOf(max).length();
for (int i = 0; i < result.length; i++) {
for (int j = 0; j < result[i].length; j++) {
System.out.printf("%"+width+"d"+" ",result[i][j]);
}
System.out.println();
}
}
private static int getInt(int r, int c){
int n = Math.max(Math.abs(r), Math.abs(c));
int standard;
if(r >= c){//대각선 아래인 경우 (2n+2)^2 - 2n
standard = (2 * n + 1) * (2 * n + 1) - (2 * n);
if(c == -n){// 기준점 대비 y축 이동한 경우
return standard - (n - r);
}else{// 기준점 대비 x축 이동한 경우
return standard + (c + n);
}
}else{//대각선 위인 경우 (2n+2)^2 + 2n
standard = (2 * n - 1) * (2 * n - 1) + (2 * n);
if(c == n){// 기준점 대비 y축 이동한 경우
return standard - (r + n);
}else{// 기준점 대비 x축 이동한 경우
return standard + (n - c);
}
}
}
}

'알고리즘&PS > PS' 카테고리의 다른 글
| [JAVA] 백준 1038 감소하는 수 (0) | 2026.02.15 |
|---|---|
| [JAVA] 백준 1025 제곱수 찾기 (0) | 2026.02.14 |
| [JAVA] 백준 1360 되돌리기 (0) | 2026.02.12 |
| [JAVA] 백준 1043 거짓말 (0) | 2025.10.04 |
| [JAVA] 백준 2413 비슷한 순열 (0) | 2025.09.22 |