알고리즘

[알고리즘] 시뮬레이션에서 자주 나오는 것들 정리

나는 나야 2024. 9. 25. 20:53

1) 일정 범위 제거 후 빈 칸이 있으면 떨어뜨리기

// 중력 작용 메서드
static void applyGravity() {
    // 모든 열에 대해 중력을 적용
    for (int col = 0; col < N; col++) {
        // 아래에서 위로 탐색하며 블록을 이동
        for (int row = N - 2; row >= 0; row--) {
            // 현재 위치가 검정 블록이거나 빈 칸인 경우 건너뜀
            if (map[row][col] == BLACK || map[row][col] == EMPTY) {
                continue;
            }
            // 블록을 아래로 이동
            moveBlock(row, col);
        }
    }
}

// 블록 한 개를 아래로 이동시키는 메서드
static void moveBlock(int x, int y) {
    int targetRow = x;

    // 블록을 아래로 이동 가능한 만큼 이동
    while (true) {
        targetRow++;
        
        // 보드를 벗어나는 경우 이동 중지
        if (targetRow >= N) {
            break;
        }
        // 검정 블록인 경우 이동 중지
        if (map[targetRow][y] == BLACK) {
            break;
        }
        // 빈 칸이 아닌 경우 이동 중지
        if (map[targetRow][y] != EMPTY) {
            break;
        }
    }

    // 이동할 위치가 원래 위치와 동일하면 이동할 필요 없음
    if (targetRow - 1 == x) {
        return;
    }

    // 블록을 아래로 이동시키고 원래 위치는 빈 칸으로 설정
    map[targetRow - 1][y] = map[x][y];
    map[x][y] = EMPTY;
}

 

2) 90도 회전

// 90 rotate
static int[][] rotate(int[][] arr) {
    int n = arr.length;
    int m = arr[0].length;
    int[][] rotate = new int[m][n];

    for (int i = 0; i < rotate.length; i++) {
        for (int j = 0; j < rotate[i].length; j++) {
            rotate[i][j] = arr[n-1-j][i];
        }
    }

    return rotate;
}