๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] ํฌ๋ ˆ์ธ ์ธํ˜•๋ฝ‘๊ธฐ ๊ฒŒ์ž„ (Python)

1. ๋ฌธ์ œ ์„ค๋ช…

๋ฌธ์ œ ๋งํฌ

  • ์ž…๋ ฅ: boards [[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]] ๋ณด๋“œ์— ์žˆ๋Š” ์ธํ˜• ์ •๋ณด
  • ์ถœ๋ ฅ: moves [1,5,3,5,1,2,1,4] ์ธํ˜•์„ ์–ด๋”” ์œ„์น˜์—์„œ ๋ฝ‘์„์ง€

2. ์ฝ”๋“œ

def solution(boards, moves):
moves = list(map(lambda x : x-1, moves)) #1์”ฉ ๋นผ์ฃผ๊ธฐ
stack = [0] #index out of range ๋ฐฉ์ง€ํ•˜์—ฌ 0 ๋„ฃ์–ด์ฃผ๊ธฐ(๋งจ ์ฒ˜์Œ์—๋„ stack[-2]๋ฅผ ๊ฒ€์‚ฌํ• ๊ฒฝ์šฐ์— ๋ฐœ์ƒ)
cnt = 0
for i in moves:
for board in boards:
if board[i] !=0:
stack.append(board[i])
board[i] = 0
if stack[-1] == stack[-2]: #์Šคํƒ์˜ ๊ฐ€์žฅ์œ„, ๊ทธ ์•„๋ž˜ ์ˆ˜๋ฅผ ๋น„๊ต
stack.pop()
stack.pop()
cnt+=2
break
return cnt

3. ํšŒ๊ณ 

  • ์ฒ˜์Œ์— ์ธ๋ฑ์Šค๋ฅผ ๋งž์ถฐ์ฃผ๊ธฐ ์œ„ํ•ด์„œ moves ๊ฐ’์„ ๋ชจ๋‘ -1 ์”ฉ ํ•ด์ฃผ์—ˆ๋‹ค. map, lambda๋ฅผ ๊ฒ€์ƒ‰ํ•˜์ง€ ์•Š๊ณ ๋„ ์“ธ์ˆ˜์žˆ๋„๋ก ์—ฐ์Šตํ•ด์•ผ๊ฒ ๋‹ค.
  • break ๋ฌธ์„ ์ž์ฃผ ์‚ฌ์šฉํ•ด๋ณด์ง„์•Š์•˜๋Š”๋ฐ, ์ด ๋ฌธ์ œ์˜ ๊ฒฝ์šฐ ๊ผญ ํ•„์š”ํ–ˆ๋‹ค.
  • ํ•œ ๋ฒˆ ๋ฐœ๊ฒฌํ•˜๊ณ  board์—์„œ ๊ฐ’์„ ๋นผ๊ณ  stack์— ๋„ฃ์—ˆ๋‹ค๋ฉด, break๋กœ for๋ฌธ์„ ๋น ์ ธ๋‚˜์™€ ๋‹ค์Œ move๋ฅผ ํ™•์ธํ•ด์•ผํ•œ๋‹ค. ๊ทธ๋ ‡์ง€ ์•Š์œผ๋ฉด ํ˜„์žฌ move ์— ํ•ด๋‹นํ•˜๋Š” board๋ฅผ ๋” ํƒ์ƒ‰ํ•ด์„œ ์ง€์šธ ๊ฒƒ์ด๊ธฐ ๋•Œ๋ฌธ์— break๋ฅผ ๊ผญ ํ•ด์ฃผ์–ด์•ผํ•œ๋‹ค.