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

🔗 [1차] 프렌즈4블록

import java.util.*;
class Solution {

    public int solution(int m, int n, String[] board) {
        char[][] arr=new char[m][n];
        int answer=0;
        for(int i=0;i<m;i++){
            arr[i]=board[i].toCharArray();
        }

        while(true){

            boolean[][]toRemove=new boolean[m][n];
            boolean found=false;

            for(int i=0;i<m-1;i++){
                for(int j=0; j<n-1;j++){
                    char current=arr[i][j];

                    if(current != ' '
                      && current == arr[i][j+1]
                      && current == arr[i+1][j]
                      && current == arr[i+1][j+1]
                      ){// 블록을 찾았다면
                        toRemove[i][j]=true;
                        toRemove[i+1][j]=true;
                        toRemove[i][j+1]=true;
                        toRemove[i+1][j+1]=true;
                        found=true;
                    }
                }
            }
            // 제거할 블록 없다면 종료
            if(!found)break;

            // 블록 카운트 및 제거
            for(int i=0;i<m;i++){
                for(int j=0;j<n;j++){
                    if(toRemove[i][j]){
                        answer++;
                        arr[i][j]=' ';
                    }
                }
            }

            // 블록 내리기
            // 열을 기준으로 행마다 빈 곳을 채워 줌
            for(int j=0;j<n;j++){

                int row=m-1;//맨 아래 행 저장(끌어 내릴 행)

                for(int i=m-1;i>=0;i--){// 아래 행부터 탐색

                    if(arr[i][j]!=' '){// 빈칸이 아니라면 

                        // 아래로 내리기
                        arr[row][j]=arr[i][j];

                        // row==i 이면 내린게 아님 그자리 그대로
                        if(row != i ) arr[i][j]=' ';

                        row --;// 윗 행으로 
                    }
                }
            }

        }
        return answer;
    }

}