기둥과 보 설치

유승선 ·2022년 9월 20일
0

프로그래머스

목록 보기
28/48

최근들어서 구현 문제에 굉장히 강하다고 생각했고 이 정도 문제는 껌이겠지 하고 접근했다가 오늘 솔직히 많이 혼났다. 분명히 문제는 잘 이해 했고 구현을 하나씩 하고 있었는데 삭제 부분에서 이것저것 많은 경우의 수를 생각하느라고 유연하게 풀지를 못했다.

기둥과 보의 생성 부분은 잘 구현했고 Matrix 를 사용해서 위치 파악해주는 부분도 생각 잘 했지만 삭제 구현에서 시간도 많이 썼고 힘들거 같아서 예전에 풀었던 답을 좀 참고했다.


#include <string>
#include <vector>
#include <bits/stdc++.h> 
using namespace std;

bool tower[101][101] = {}; 
bool paper[101][101] = {}; 

bool checkTower(int x, int y, int n){
    //땅에 있을때 확인, 오른쪽 끝에 있는지 확인, 왼쪽 끝에 있는지 확인, 밑에 기둥있는지 확인 
    return (y == 0 || paper[x][y] || paper[x-1][y] || tower[x][y-1]);
}

bool checkPaper(int x, int y, int n){
    return(tower[x][y-1] || tower[x+1][y-1] || paper[x-1][y] && paper[x+1][y]); 
}

vector<vector<int>> solution(int n, vector<vector<int>> build_frame) {
    vector<vector<int>> answer;
    
    for(vector<int>& v : build_frame){
        int x = v[0], y = v[1], structure = v[2], command = v[3];  
        
        
        if(command == 1){
            if(structure == 0 && checkTower(x,y,n)){ //지을 수 있는 기둥인지 
                tower[x][y] = true; 
            }
            if(structure == 1 && checkPaper(x,y,n)){ //지을 수 있는 보 인지 
                paper[x][y] = true; 
            }
        }
        
        if(command == 0){
            if(structure == 0){
                tower[x][y] = false; 
                bool can = true; 
                if(tower[x][y+1] && !checkTower(x,y+1,n)) can = false; 
                if(paper[x][y+1] && !checkPaper(x,y+1,n)) can = false; 
                if(paper[x-1][y+1] && !checkPaper(x-1,y+1,n)) can = false; 
                    
                if(!can) tower[x][y] = true; 
            }
            if(structure == 1){
                paper[x][y] = false; 
                bool can = true; 
                if(tower[x][y] && !checkTower(x,y,n)) can = false; 
                if(tower[x+1][y] && !checkTower(x+1,y,n)) can = false; 
                if(paper[x-1][y] && !checkPaper(x-1,y,n)) can = false; 
                if(paper[x+1][y] && !checkPaper(x+1,y,n)) can = false; 
                
                if(!can) paper[x][y] = true; 
            }
        }
    }
    
    for(int i = 0; i <= n; i++){
        for(int j = 0; j <= n; j++){
            if(tower[i][j]) answer.push_back({i,j,0}); 
            if(paper[i][j]) answer.push_back({i,j,1}); 
        }
    }
    return answer;
}

내가 실수했던 부분은 기둥의 위치를 visited로 표시할때 좀 더 구분을 잘 했어야 했는데 헷갈리게 작성했다. 너무나도 아쉬운 문제고 나중에는 더 잘 하고 싶다.

배운점
1. Matrix 구현
2. 시뮬레이션

profile
성장하는 사람

0개의 댓글