Notice
Recent Posts
Recent Comments
Link
«   2025/07   »
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

코딩응급실

프로그래머스: [1차] 프렌즈4블록 본문

Java

프로그래머스: [1차] 프렌즈4블록

Daeryuk Kim 2024. 3. 26. 22:45
import java.util.*;

public class Solution {
    public int solution(int m, int n, String[] board) {
        char[][] map = new char[m][n];
        // 문자열 배열을 2차원 char 배열로 변환
        for (int i = 0; i < m; i++) {
            map[i] = board[i].toCharArray();
        }

        int count = 0; // 지워진 블록의 총 개수

        while (true) {
            List<int[]> toRemove = new ArrayList<>(); // 이번 라운드에 지워질 블록들의 위치 저장
            // 2x2 체크
            for (int i = 0; i < m - 1; i++) {
                for (int j = 0; j < n - 1; j++) {
                    char block = map[i][j];
                    if (block != ' ' && block == map[i][j + 1] && block == map[i + 1][j] && block == map[i + 1][j + 1]) {
                        toRemove.add(new int[]{i, j});
                        toRemove.add(new int[]{i, j + 1});
                        toRemove.add(new int[]{i + 1, j});
                        toRemove.add(new int[]{i + 1, j + 1});
                    }
                }
            }

            if (toRemove.isEmpty()) break; // 지워질 블록이 없으면 반복 종료

            // 중복 위치 제거 및 블록 지우기
            for (int[] pos : toRemove) {
                if (map[pos[0]][pos[1]] != ' ') {
                    map[pos[0]][pos[1]] = ' '; // 블록 지우기
                    count++;
                }
            }

            // 블록 아래로 떨어뜨리기
            for (int col = 0; col < n; col++) {
                for (int row = m - 1; row >= 0; row--) {
                    if (map[row][col] == ' ') {
                        int nextRow = row - 1;
                        while (nextRow >= 0 && map[nextRow][col] == ' ') {
                            nextRow--;
                        }
                        if (nextRow >= 0) {
                            map[row][col] = map[nextRow][col];
                            map[nextRow][col] = ' ';
                        }
                    }
                }
            }
        }

        return count;
    }

    public static void main(String[] args) {
        Solution sol = new Solution();
        int m = 4;
        int n = 5;
        String[] board = {"CCBDE", "AAADE", "AAABF", "CCBBF"};
        System.out.println(sol.solution(m,n,board));
    }
}