문제 링크
코드
def solution(commands):
answer = []
cells = []
for command in commands:
cmd = command.split()
if cmd[0] == "UPDATE":
if len(cmd) == 4:
def update1(r, c, v):
for cell in cells:
if (r, c) in cell[0]:
cell[1] = v
return
cells.append([{(r, c)}, v])
update1(int(cmd[1]), int(cmd[2]), cmd[3])
else:
def update2(v1, v2):
for cell in cells:
if cell[1] == v1:
cell[1] = v2
update2(cmd[1], cmd[2])
elif cmd[0] == "MERGE":
def findcell(r, c):
for i, cell in enumerate(cells):
if (r, c) in cell[0]:
return cells.pop(i)
return [{(r, c)}, "EMPTY"]
def merge(r1, c1, r2, c2):
cell1 = findcell(r1, c1)
cell2 = findcell(r2, c2)
if cell1[1] == "EMPTY":
cell1[1] = cell2[1]
cells.append([cell1[0] | cell2[0], cell1[1]])
merge(int(cmd[1]), int(cmd[2]), int(cmd[3]), int(cmd[4]))
elif cmd[0] == "UNMERGE":
def unmerge(r, c):
for cell in cells:
if (r, c) in cell[0]:
cell[0] = {(r, c)}
return
unmerge(int(cmd[1]), int(cmd[2]))
else:
def printf(r, c):
for cell in cells:
if (r, c) in cell[0]:
return cell[1]
return "EMPTY"
answer.append(printf(int(cmd[1]), int(cmd[2])))
return answer
리뷰
- 단순 구현 문제였지만 셀을 저장하기 위한 구조를 정하는 것이 어려웠다
- 처음에는 50 * 50 표에서 child cell이 parent cell을 참조하는 구조로 구현하려고 했지만 unmerge에서 child cell을 찾는 과정이 어려웠다
- 그래서 cell group을 set으로 저장하는 리스트를 만들었더니 더 쉽게 풀렸다