우당탕탕 개발일지

[프로그래머스] Level 2. 거리두기 확인하기 본문

Algorithm(c++)/Level 2

[프로그래머스] Level 2. 거리두기 확인하기

devchop 2025. 3. 7. 11:59

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

 

프로그래머스

SW개발자를 위한 평가, 교육, 채용까지 Total Solution을 제공하는 개발자 성장을 위한 베이스캠프

programmers.co.kr

 

해결 방법

  1. 테이블에서 P가 나오면, 검사범위를 설정한다.
  2. 그 범위안에서 P가 나왔을때 만약 맨해튼거리가 1이면 false를 바로 리턴한다.
  3. 아니라면, 두개의 P자리  (x,y) 와 (i,j) 사이에 X가 한개라도 없으면 바로 false를 리턴한다. 

 

#include <string>
#include <vector>
#include <cmath>
#include <iostream>

using namespace std;

bool checkPlace(vector<string> tables, int i, int j){
    //검사해야하는 인덱스들
    vector<vector<int>> checks = {
        {i-2,j},
        {i-1,j-1},{i-1,j},{i-1,j+1},
        {i,j-2},{i,j-1},{i,j+1},{i,j+2},
        {i+1,j-1},{i+1,j},{i+1,j+1},
        {i+2,j}
    };
    
    
    for(int idx =0; idx<checks.size(); idx++){
        int x = checks[idx][0]; int y = checks[idx][1];
        
        if(x < 0 || x >= tables.size() || y <0 || y >=tables[x].size()) continue;
        if(tables[x][y] != 'P') continue;
        if(abs(x-i) + abs(y-j) <=1) return false;
    
        for(int row =  min(x,i) ; row <= max(x,i) ; row ++){
            for(int col = min(y,j); col <=max(y,j); col ++){     
                if(row == x && col ==y) continue;
                if(row == i && col == j) continue;
                if(tables[row][col] != 'X') return false;
            }
        }
        
    }
    
    return true;
    
}

bool isSafeRoom(vector<string> tables){
    for(int i=0; i<tables.size(); i++){
        for(int j=0; j<tables[i].size(); j++){
            if(tables[i][j]=='P'){
                bool safe= checkPlace(tables,i,j);  
                if(!safe) return false;
            } 
        }
    }    
    return true;
}

vector<int> solution(vector<vector<string>> places) {
    vector<int> answer;
    for(int i=0; i<places.size(); i++){
 
        bool safe = isSafeRoom(places[i]);
        answer.push_back(safe?1:0);
    }
    return answer;
}