programmers_[1차] 프렌즈4블록_java

2023. 4. 13. 15:07Algorithm/Programmers

728x90

https://school.programmers.co.kr/learn/courses/30/lessons/17679

 

프로그래머스

코드 중심의 개발자 채용. 스택 기반의 포지션 매칭. 프로그래머스의 개발자 맞춤형 프로필을 등록하고, 나와 기술 궁합이 잘 맞는 기업들을 매칭 받으세요.

programmers.co.kr

import java.util.*;

class Solution {
    private static int[][] delta = {{0,1}, {1,1}, {1, 0}, {0,0}}; // 우 우하 하 정지
    
    public int solution(int m, int n, String[] board) {
        int answer = 0;
        
        while(true){
            Queue<Point> crashList = new LinkedList<>();
            for(int i = 0; i< m; i++){
                for(int j = 0; j < n; j++){
                    if(board[i].charAt(j) != '0')
                        findSquare(i, j, board[i].charAt(j), crashList, m, n, board);
                }
            }
            if(crashList.isEmpty()){ // 더이상 파괴 가능한 것이 없는 경우
                break;
            }            
            answer += crash(crashList, board); // 파괴
            assemble(m, n, board); // 조립
        }
        
        return answer;
    }
    
    public void findSquare(int y, int x, char target, Queue<Point> crashList, int m, int n, String[] board){
        for(int i = 0; i<3; i++){ // 우, 우하, 하 가 같은 것인지 탐색
            int nexty = y + delta[i][0];
            int nextx = x + delta[i][1];
            if(0 > nexty || nexty >= m || 0 > nextx || nextx >= n || board[nexty].charAt(nextx) != target){
                return; // 2 * 2 가 성립하지 않는 경우 패스
            }            
        }
        for(int i = 0; i<4; i++){ // 성립하는 경우 crashList에 추가
            int nexty = y + delta[i][0];
            int nextx = x + delta[i][1];
            crashList.offer(new Point(nexty, nextx));         
        }
        return;        
    }
    
    public int crash(Queue<Point> crashList, String[] board){
        int cnt = 0;
        while(!crashList.isEmpty()){
            Point now = crashList.poll();
            if(board[now.y].charAt(now.x) != '0') cnt++;
            board[now.y] = board[now.y].substring(0, now.x) + '0' + board[now.y].substring(now.x + 1);
        }
        return cnt;
    }
    
    public void assemble(int m, int n, String[] board){
        char[][] map = new char[m][n];
        for(int i = 0; i < n; i++){
            Stack<Character> stack = new Stack<>();
            for(int j = 0; j<m; j++){
                if(board[j].charAt(i) != '0'){
                    stack.push(board[j].charAt(i));
                }
            }
            int idx = m-1;
            for(int j = m-1; j>=0; j--){
                if(!stack.isEmpty()){
                    map[j][i] = stack.pop();
                }else{
                    map[j][i] = '0';
                }
            }
        }
        
        for(int i = 0; i<m; i++){
            board[i] = String.valueOf(map[i]);
        }
        return;
    }
    
    public class Point{
        int y, x;
        public Point(int y, int x){
            this.y = y;
            this.x = x;
        }
    }
}