본문 바로가기
알고리즘/프로그래머스

[ 프로그래머스 / 구현 ] 프렌즈4블록 (KaKao)

by 뎁꼼 2020. 7. 3.

1. 문제


 

 

코딩테스트 연습 - [1차] 프렌즈4블록

프렌즈4블록 블라인드 공채를 통과한 신입 사원 라이언은 신규 게임 개발 업무를 맡게 되었다. 이번에 출시할 게임 제목은 프렌즈4블록. 같은 모양의 카카오프렌즈 블록이 2×2 형태로 4개가 붙��

programmers.co.kr

 

 

2. 소스코드


- 구현 문제. 블럭 문제는 유형도 비슷하고, 블럭을 삭제하는 로직만 잘 처리하면 나머지는 무난 무난하고 히든 케이스도 없어서 AC받기가 편하다.

- 로직은

1) 게임 실행

2) 삭제할 블럭이 있는가?

3) 있다면, 블럭을 삭제하고 drop한 뒤 2)로 부터 다시 실행

4) 없다면 종료.

 

소스코드

#include <string>
#include <vector>
#include <queue>
#include <iostream>
#define DEL_MARK '*'
using namespace std;
queue < pair<int, int> > del_point;
int answer, M, N;

bool find(vector<string>& board) {
    bool change = false;
    for (int i = 1; i < M; ++i) {
        for (int j = 1; j < N; ++j) {
            if (board[i][j] == DEL_MARK) continue;
            if (board[i - 1][j] == board[i][j] and
                board[i - 1][j - 1] == board[i][j] and
                board[i][j - 1] == board[i][j]) {
                del_point.push({ i,j });
                del_point.push({ i - 1,j - 1 });
                del_point.push({ i,j - 1 });
                del_point.push({ i - 1,j });
                change = true;
            }
        }
    }
    return change;
}

void delblock(vector<string>& board) {
    while (!del_point.empty()) {
        auto cur = del_point.front();
        int x = cur.first;
        int y = cur.second;
        if (board[x][y] != DEL_MARK) {
            board[x][y] = DEL_MARK;
            answer++;
        }
        del_point.pop();
    }
    return;
}

void drop(vector<string>& board) {
    for (int i = M - 1; i >= 0; --i)
        for (int j = N - 1; j >= 0; --j) {
            if (board[i][j] == DEL_MARK) {
                int nx = i;
                while (nx--) {
                    if (board[nx][j] != DEL_MARK) {
                        swap(board[nx][j], board[i][j]);
                        break;
                    }
                }
            }
        }
    return;
}

void playGame(vector<string>& board) {
    if (find(board)) {
        delblock(board);
        drop(board);
        playGame(board);
    }
    return;
}

int solution(int m, int n, vector<string> board) {
    M = m; N = n;
    playGame(board);
    return answer;
}