Skip to content

Conversation

@sunha20
Copy link
Contributor

@sunha20 sunha20 commented Jan 6, 2026

🚀 이슈 번호

Resolve: {#2274}

🧩 문제 해결

스스로 해결:

🔎 접근 과정

문제 해결을 위한 접근 방식을 설명해주세요.

  • 🔹 어떤 알고리즘을 사용했는지 그래프탐색/구현
  • 🔹 어떤 방식으로 접근했는지

이동방향 회전, 주사위 굴리기 등 방향 관련으로 체크해야할 것이 많았음. 직접 몇가지 경우를 적어보면서 규칙을 찾고, 따로 함수로 빼서 구현. (rolll(), rotate~~())

연결된 같은 수를 가진 칸은 고정된 값이므로, 한번 dfs를 돌려 구한 값을 다른 배열에 저장해 중복 연산을 줄였다. (setCount())

시뮬레이션 문제의 경우 작은 단계로 나누고 순서에 따라 함수 이름을 먼저 적어 놓고, 각 로직을 하나씩 구현하는게 좀 더 안정적인 거 같음.

⏱️ 시간 복잡도

시간 복잡도 분석을 작성해주세요.
최악의 경우 수행 시간은 어느 정도인지 분석합니다.

  • Big-O 표기법: O(NM)
  • 이유:
    그래프 탐색: N*M개의 노드에 대해서 4방향 체크를 함 + 백트래킹과 다르게 visited를 초기화 하지 않음(하는 경우 약 (3^NM)?)탐색이 이루어지기 때문.

💻 구현 코드

import java.io.*;
import java.util.*;

public class Main {
    static int[][] gp, visited, count;
    static int[] dice = {6,3,5};    // 바닥면, 오른쪽 면, 아래쪽 면
    static int[][] offset = {{0,1}, {1,0}, {0,-1}, {-1,0}};
    static int dir;                 // 0=동 / 1=남 / 2=서 / 3=북
    static int N, M, K;
    static ArrayList<int[]> edit_count;

    public static void main(String[] args) throws IOException {
        // get input
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String[] temp = br.readLine().split(" ");
        N = Integer.parseInt(temp[0]);
        M = Integer.parseInt(temp[1]);
        K = Integer.parseInt(temp[2]);

        // set graph
        gp = new int[N][M];
        visited = new int[N][M];
        count = new int[N][M];

        for (int n=0; n<N; n++) {
            temp = br.readLine().split(" ");
            for (int m=0; m<M; m++) {
                gp[n][m] = Integer.parseInt(temp[m]);
            }
        }

        // for 0 -> K
        int x = 0, y = 0, score = 0;
        for (int k=0; k<K; k++) {
            // move
            x += offset[dir][0];
            y += offset[dir][1];

            // 갈  수 없는 칸일 때
            if (x < 0 || x >= N || y < 0 || y >= M) {
                x -= offset[dir][0];
                y -= offset[dir][1];
                rotateOppo();
                x += offset[dir][0];
                y += offset[dir][1];
            }

            // roll
            roll();

            // 점수 계산(count or dfs+setCount -> 두번에 나눠서 하는 거 좀 비효율 적임...)
            int adjecanct;
            if (count[x][y] != 0) adjecanct = count[x][y];
            else {
                edit_count = new ArrayList<>();
                adjecanct = dfs(x, y);
                setCount(adjecanct);
            }
            score += adjecanct * gp[x][y];

            // rotate
            if (dice[0] > gp[x][y]) rotateCW();
            else if (dice[0] < gp[x][y]) rotateCCW();
        }
        System.out.println(score);
    }

    static int dfs(int x, int y) {
        int val = gp[x][y];
        int result = 1; // 자기 자신 포함
        visited[x][y] = 1;
        edit_count.add(new int[] {x, y});

        // for 0->4 하면서 상하좌우 탐색
        for (int o=0; o<4; o++) {
            int nx = x+offset[o][0];
            int ny = y+offset[o][1];

            // 가능한 경우(경계 안이고, 같은 수를 가졌으며, visit하지 않음)
            if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
                if (visited[nx][ny] == 0 && gp[nx][ny] == val){
                    result += dfs(nx, ny);
                    // visited[nx][ny] = 0; -> 경로 찾는게 아니라 그냥 해도 될 것같은데... 안바꾸고.
                }
            }
        }
        return result;
    }

    static void setCount(int cnt) {
        for (int[] pos: edit_count) {
            count[pos[0]][pos[1]] = cnt;
        }
    }

    static void rotateCW() {
        dir = (dir+1)%4;
    }

    static void rotateCCW() {
        dir = (dir+3)%4;
    }

    static void rotateOppo() {
        dir = (dir+2)%4;
    }

    static void roll( ) {
        int[] new_dice = dice;

        switch (dir) {
            case 0:     // 동
                new_dice = new int[] {dice[1], 7 - dice[0], dice[2]};
                break;
            case 1:     // 남
                new_dice = new int[] {dice[2], dice[1], 7 - dice[0]};
                break;
            case 2:     // 서
                new_dice = new int[] {7 - dice[1], dice[0], dice[2]};
                break;
            case 3:     // 북
                new_dice = new int[] {7 - dice[2], dice[1], dice[0]};
                break;
        }

        dice = new_dice;
    }
}

@sunha20 sunha20 linked an issue Jan 6, 2026 that may be closed by this pull request
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

260106 : 코딩테스트

2 participants