https://programmers.co.kr/learn/courses/30/lessons/60061
전형적인 구현 문제였다. 완성된 코드의 틀을 짜는 데에는 대충 1시간 남짓 걸린 것 같은데 뭐가 틀린지 몰라서 헤매는 지옥같은 디버깅에 3시간 정도를 썼다.
풀지 못하던 이유는 기둥과 보의 좌표를 계산할 때의 잘못이었다.
([arr_xy[0], arr_xy[1] - 1, 0] in collid)
를
(arr_xy in [[i[0], i[1]-1] for i in collid])
이렇게 기둥과 보의 좌표를 계산할 때 왜 collid나 bo에서 따로 리스트를 빼서 비교를 했는지 모르겠다. 이 과정에서 헷갈려서 3시간을 보내버렸는데, 다음부터 이런 문제를 풀 때에는 기준 리스트가 아니라 들어온 데이터를 변형하는 식으로 조건식을 작성해야 한다고 느꼈다.
#p329
#순차적으로 명령 수행할 때마다 iscorrect호출하고 되면 진행 안되면 패스
#[x, y, a, b] - x, y는 좌표, a는 0이면 기둥 1이면 보, b는 0은 삭제 1은 설치
import copy
def solution(n, build_frame):
answer = [[]]
answer = []
def iscorrect(answer):#arr은 좌표, answer는 현재 공사 현황 좌표들
floor = [[i, 0] for i in range(n+1)] #바닥 타일 좌표
bo = [i for i in answer if i[2] == 1] #보 좌표
collid = [i for i in answer if i[2] == 0] #기둥 좌표
for arr in answer:
arr_xy = [arr[0], arr[1]] #arr좌표
if arr[2] == 1: #보일 경우
if ([arr_xy[0], arr_xy[1] - 1, 0] in collid) or ([arr_xy[0]+1, arr_xy[1] - 1, 0] in collid): #한쪽 끝이 기둥 위에 있음
continue
elif [arr_xy[0] - 1, arr_xy[1], 1] in bo and [arr_xy[0] + 1, arr_xy[1], 1] in bo: #양쪽 끝부분이 다른 보와 동시에 연결
continue
else:
return False
elif arr[2] == 0: #기둥일 경우
if arr_xy in floor: #바닥에 있음
continue
elif [arr_xy[0], arr_xy[1], 1] in bo or [arr_xy[0] - 1, arr_xy[1], 1] in bo: #보의 한쪽 끝에 있음
continue
elif [arr_xy[0], arr_xy[1] - 1, 0] in collid: #다른 기둥 위에 있을 때
continue
else:
return False
return True
for command in build_frame:
answer_rep = copy.deepcopy(answer)
arr = [command[0], command[1], command[2]]
if command[3] == 0: #삭제
if arr in answer_rep:
answer_rep.remove(arr)
if iscorrect(answer_rep):
answer.remove(arr)
elif command[3] == 1: #설치
answer_rep.append(arr)
if iscorrect(answer_rep) and arr not in answer:
answer.append(arr)
answer.sort(key = lambda x : (x[0],x[1],x[2]))
return answer
solution(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]])