알고리즘/프로그래머스
[python] 크레인 인형뽑기 게임 (2019 카카오 개발자 겨울 인턴십)
Garonguri
2021. 8. 31. 00:48
728x90

This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
sys.setrecursionlimit(10**9) | |
def solution(board, moves): | |
answer = 0 | |
box, baguni = [], [] | |
for i in range(len(board)): | |
sub = [] | |
for line in board: | |
if line[i] != 0: | |
sub.append(line[i]) | |
box.append(sub) | |
exsub, sub = 0, 0 | |
for i in range(len(moves)): | |
position = moves[i]-1 | |
if box[position]: | |
sub = box[position].pop(0) | |
print(baguni) | |
if exsub == sub: | |
baguni.pop(-1) | |
if baguni: | |
exsub = baguni[-1] | |
else: | |
exsub =0 | |
answer +=1 | |
#print(baguni) | |
else: | |
baguni.append(sub) | |
if baguni: | |
exsub = baguni[-1] | |
else: | |
exsub =0 | |
#print("sub, ex", sub, exsub) | |
else: | |
pass | |
print(answer*2) | |
return answer*2 |
[한줄평]
경우를 나누어 잘 따라간다면 비교적 쉽게 풀 수 있던 문제였다.
[풀이]
1. 가로 축으로 입력 받은 board list를 세로 축으로 읽은 'box'라는 리스트를 만들었다.
2. box는 번호가 1부터 시작하므로, moves에서 입력받은 숫자에 -1을 해준 것이 몇 번째 box인지를 나타낸다.
3. 만약 박스가 비었다면, pass한다.
# exsub = 현재 바구니에 맨 위에 있는 인형, sub = 이제 바구니에 넣어야 할 인형
4. 박스가 비지 않았고, exsub != sub 인 경우엔, 바구니에 sub를 추가하고 exsub을 바꿔준다.
5. 박스가 비지 않았고, exsub == sub인 경우엔, 바구니에 sub을 넣지 않고 exsub을 지운 뒤 answer++ 해준다.
6. 이 때 바구니가 비지 않았을 경우는 바구니의 맨 위 인형을 exsub로 만들고, 바구니가 비었을 경우 exsub를 0으로 초기화한다.
7. exsub == sub인 경우 answer을 1씩 늘어났는데 실제로 없어진 인형은 두개이므로 answer*2를 리턴해준다.

728x90