programmers_[1차] 프렌즈4블록_java
2023. 4. 13. 15:07ㆍAlgorithm/Programmers
728x90
https://school.programmers.co.kr/learn/courses/30/lessons/17679
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;
}
}
}
'Algorithm > Programmers' 카테고리의 다른 글
programmers_2 x n 타일링_java (0) | 2023.04.13 |
---|---|
programmers_2개 이하로 다른 비트_java (0) | 2023.04.13 |
programmers_게임 맵 최단거리_java (0) | 2023.04.11 |
programmers_[3차] 파일명 정렬_java (0) | 2023.04.11 |
programmers_모음 사전_java (0) | 2023.04.11 |