https://programmers.co.kr/learn/courses/30/lessons/60061?language=python3

 

코딩테스트 연습 - 기둥과 보 설치

5 [[1,0,0,1],[1,1,1,1],[2,1,0,1],[2,2,1,1],[5,0,0,1],[5,1,0,1],[4,2,1,1],[3,2,1,1]] [[1,0,0],[1,1,1],[2,1,0],[2,2,1],[3,2,1],[4,2,1],[5,0,0],[5,1,0]] 5 [[0,0,0,1],[2,0,0,1],[4,0,0,1],[0,1,1,1],[1,1,1,1],[2,1,1,1],[3,1,1,1],[2,0,0,0],[1,1,1,0],[2,2,0,1]] [[

programmers.co.kr



Solution

def check(answer):
    for i in answer:
        flag = False
        x, y, structure = i[0], i[1], i[2]
        # 기둥(0)
        if structure == 0:
            if y == 0 or [x-1, y, 1] in answer or [x, y, 1] in answer or [x, y-1, 0] in answer:
                continue
            return False
        # 보(1)
        else:
            if [x, y-1, 0] in answer or [x+1, y-1, 0] in answer:
                continue
            if [x-1, y, 1] in answer and [x+1, y, 1] in answer:
                continue
            return False
    return True
    
def solution(n, build_frame):
    answer = []
    for i in build_frame:
        x, y, structure, setting = i[0], i[1], i[2], i[3]
        # 설치
        if setting == 1:
            answer.append([x, y, structure])
            if not check(answer):
                answer.remove([x, y, structure])
        # 삭제
        else:
            answer.remove([x, y, structure])
            if not check(answer):
                answer.append([x, y, structure])
        #print(answer)
    answer = sorted(answer)
    return answer

 

시뮬레이션 문제이다.

설치할 때는 먼저 answer에 해당 구조물을 넣고, check에서 answer에 있는 모든 구조물들이 조건에 맞는지 확인한다. 똑같이 삭제할 때는 answer에서 구조물을 삭제해보고, check에서 조건을 확인한다. 

 

        # 설치
        if setting == 1:
            answer.append([x, y, structure])
            if not check(answer):
                answer.remove([x, y, structure])
        # 삭제
        else:
            answer.remove([x, y, structure])
            if not check(answer):
                answer.append([x, y, structure])

 

기둥일 경우의 조건은 다음과 같고 차례대로 검사하면 아래와 같다.

  1. 바닥 위에 있을 때
  2. 보의 한쪽 끝 부분에 있을 때
  3. 다른 기둥 위에 있을 때
if structure == 0:
    if y == 0 or [x-1, y, 1] in answer or [x, y, 1] in answer or [x, y-1, 0] in answer:
        continue
    return False

 

보일 경우의 조건은 다음과 같고 차례대로 검사하면 아래와 같다.

  1. 한쪽 끝 부분이 기둥 위에 있을 때
  2. 양쪽 끝 부분이 다른 보와 동시에 연결되어 있을 때
else:
    if [x, y-1, 0] in answer or [x+1, y-1, 0] in answer:
        continue
    if [x-1, y, 1] in answer and [x+1, y, 1] in answer:
        continue
    return False

 

 

 


생강강

,