[자바] SWEA 6109 : 추억의 2048 게임 (D4)
풀이
방향성 생각
- 각 방향으로 밀어주는 경우를 구현해야한다.
전체코드
import java.io.*;
import java.util.*;
public class Solution {
static int TC, N;
static int[][] arr;
// 푸시하려는 방향으로 잃어서 2중 for문을 통해서 밀어주는 로직 구현
static int[] push(int[] temp) {
for (int i=0; i<N-1; i++) {
// 현재 위치에 밀게 없으면 다음으로
if (temp[i]==0) continue;
// 다음 위치에 아무것도 없으면 패스
for (int j=i+1; j<N; j++) {
if (temp[j]==0) continue;
// 다음 위치에 합쳐질게 있고 같은 숫자면 합쳐주기
if (temp[j] > 0 && temp[i] == temp[j]) {
temp[i] *= 2;
temp[j] = 0;
}
break;
}
}
return temp;
}
public static void main(String[] args) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
StringBuilder sb = new StringBuilder();
TC = Integer.parseInt(br.readLine());
for (int tc=1; tc<=TC; tc++) {
st = new StringTokenizer(br.readLine());
N = Integer.parseInt(st.nextToken());
char cmd = st.nextToken().charAt(0);
arr = new int[N][N];
for (int y=0; y<N; y++) {
st = new StringTokenizer(br.readLine());
for (int x=0; x<N; x++) {
arr[y][x] = Integer.parseInt(st.nextToken());
}
}
int[][] answer = new int[N][N];
if (cmd == 'u') {
// read col
for (int x=0; x<N; x++) {
int[] temp = new int[N];
for (int y=0; y<N; y++) {
temp[y] = arr[y][x];
}
// push
int[] new_temp = push(temp);
int cnt = 0;
for (int i=0; i<N; i++) {
if (new_temp[i] > 0) {
answer[cnt][x] = new_temp[i];
cnt += 1;
}
}
}
} else if (cmd == 'd') {
// read col
for (int x=0; x<N; x++) {
int[] temp = new int[N];
for (int y=0; y<N; y++) {
temp[y] = arr[N-1-y][x];
}
//push
int[] new_temp = push(temp);
int cnt = 0;
for (int i=0; i<N; i++) {
if (new_temp[i] > 0) {
answer[N-1-cnt][x] = new_temp[i];
cnt += 1;
}
}
}
} else if (cmd == 'l') {
// read row
for (int y=0; y<N; y++) {
int[] temp = new int[N];
for (int x=0; x<N; x++) {
temp[x] = arr[y][x];
}
int[] new_temp = push(temp);
int cnt = 0;
for (int i=0; i<N; i++) {
if (new_temp[i] > 0) {
answer[y][cnt] = new_temp[i];
cnt += 1;
}
}
}
} else if (cmd == 'r') {
for (int y=0; y<N; y++) {
int[] temp = new int[N];
for (int x=0; x<N; x++) {
temp[x] = arr[y][N-1-x];
}
int[] new_temp = push(temp);
int cnt = 0;
for (int i=0; i<N; i++) {
if (new_temp[i] > 0) {
answer[y][N-1-cnt] = new_temp[i];
cnt += 1;
}
}
}
}
sb.append('#').append(tc).append('\n');
for (int i=0; i<N; i++) {
for (int j=0; j<N; j++) {
sb.append(answer[i][j]).append(" ");
}
sb.append("\n");
}
}
System.out.println(sb.toString());
}
}
코멘트
- .
'Algorithm > Simulation' 카테고리의 다른 글
[파이썬] SWEA 5644 : 무선 충전 (TEST) (0) | 2025.03.09 |
---|---|
[자바] SWEA 2382 : 미생물 격리 (test) (0) | 2025.03.09 |
[자바] SWEA 1873 : 상호의 배틀필드 (D3) (0) | 2025.03.09 |
[파이썬,자바] 프로그래머스 : 지게차와 크레인 (레벨2) (0) | 2025.02.11 |
[파이썬] 프로그래머스 : 혼자 놀기의 달인 (레벨2) (0) | 2024.06.10 |
[파이썬] 코드트리 : 코드트리 투어 (골드2) (0) | 2024.05.11 |
[파이썬] 코드트리 : 고대 문명 유적 탐사 (골드4) (0) | 2024.05.01 |
댓글