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

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค/PythonํŒŒ์ด์ฌ] ํ”„๋ Œ์ฆˆ4๋ธ”๋ก(2018 ์นด์นด์˜ค ์ฝ”๋”ฉํ…Œ์ŠคํŠธ 1์ฐจ)

meeeeejin 2021. 5. 3. 22:09

๋ฌธ์ œ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/17679

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - [1์ฐจ] ํ”„๋ Œ์ฆˆ4๋ธ”๋ก

ํ”„๋ Œ์ฆˆ4๋ธ”๋ก ๋ธ”๋ผ์ธ๋“œ ๊ณต์ฑ„๋ฅผ ํ†ต๊ณผํ•œ ์‹ ์ž… ์‚ฌ์› ๋ผ์ด์–ธ์€ ์‹ ๊ทœ ๊ฒŒ์ž„ ๊ฐœ๋ฐœ ์—…๋ฌด๋ฅผ ๋งก๊ฒŒ ๋˜์—ˆ๋‹ค. ์ด๋ฒˆ์— ์ถœ์‹œํ•  ๊ฒŒ์ž„ ์ œ๋ชฉ์€ "ํ”„๋ Œ์ฆˆ4๋ธ”๋ก". ๊ฐ™์€ ๋ชจ์–‘์˜ ์นด์นด์˜คํ”„๋ Œ์ฆˆ ๋ธ”๋ก์ด 2ร—2 ํ˜•ํƒœ๋กœ 4๊ฐœ๊ฐ€ ๋ถ™

programmers.co.kr

 

 

๋ฌธ์ œ ์„ค๋ช…

board ๋ฌธ์ž์—ด ๋ฐฐ์—ด ์ž…๋ ฅ์„ ๋ฆฌ์ŠคํŠธ๋กœ ๋ฐ”๊ฟ”์„œ ์ฒ˜๋ฆฌํ–ˆ์Šต๋‹ˆ๋‹ค. ์ด ๋’ค์— ๋ธ”๋ก์ด ๋” ์ด์ƒ ์ง€์›Œ์ง€์ง€ ์•Š์„ ๋•Œ๊นŒ์ง€ while๋ฌธ์„ ๋Œ๋ฉด์„œ ๋ธ”๋ก์„ ์ง€์› ์Šต๋‹ˆ๋‹ค. 

 

while๋ฌธ์—์„œ ํ•œ ๋ฒˆ์˜ ๋ฐ˜๋ณต๋งˆ๋‹ค ๋‹ค์Œ์„ ์‹คํ–‰ํ•ฉ๋‹ˆ๋‹ค. 

  1. mxn ํฌ๊ธฐ์˜ remove ๋ฐฐ์—ด์„ 0์œผ๋กœ ์ดˆ๊ธฐํ™”ํ•ฉ๋‹ˆ๋‹ค. 
  2. (0, 0) ๋ธ”๋ก๋ถ€ํ„ฐ (m-1, n-1) ๋ธ”๋ก๊นŒ์ง€ ๊ฐ™์€ ๋ชจ์–‘์˜ 2x2 ๋ธ”๋ก์„ ์ฐพ์œผ๋ฉด ํ•ด๋‹น ์ธ๋ฑ์Šค์˜ remove ๋ฐฐ์—ด์— 1๋กœ ํ‘œ์‹œํ•ฉ๋‹ˆ๋‹ค. 
  3. remove์— 1๋กœ ํ‘œ์‹œ๋œ ๋ธ”๋ก์˜ ๊ฐœ์ˆ˜๋ฅผ count์— ์ €์žฅํ•ฉ๋‹ˆ๋‹ค. (count : ํ•œ ํ…€์— ์ง€์›Œ์ง„ ๋ธ”๋ก์˜ ๊ฐœ์ˆ˜)
  4. ์ง€์›Œ์ง„ ๋ธ”๋ก์˜ ๊ฐœ์ˆ˜๋ฅผ answer์— ๋”ํ•ฉ๋‹ˆ๋‹ค. 
  5. ์ง€์›Œ์ง„ ๋ธ”๋ก์ด ์—†์„ ๊ฒฝ์šฐ while๋ฌธ์„ ๋น ์ ธ๋‚˜์˜ต๋‹ˆ๋‹ค. 

 

 

 

์†Œ์Šค์ฝ”๋“œ
def solution(m, n, board):
    answer = 0
    for i in range(len(board)):
        board[i] = list(board[i])

    while True:
        # ๊ฐ™์€ ๋ชจ์–‘์˜ 2X2 ๋ธ”๋ก์„ ์ฐพ์œผ๋ฉด remove ๋ฐฐ์—ด์— 1๋กœ ํ‘œ์‹œ
        remove = [[0]*n for _ in range(m)]
        for i in range(m - 1):
            for j in range(n - 1):
                if board[i][j] != 0 and board[i][j] == board[i][j + 1] and board[i][j] == board[i + 1][j] and board[i][j] == board[i + 1][j + 1]:
                    remove[i][j], remove[i][j + 1], remove[i + 1][j], remove[i + 1][j + 1] = 1, 1, 1, 1
        # ์ง€์›Œ์ง„ ๋ธ”๋ก ๊ฐœ์ˆ˜ ์„ธ๊ธฐ
        count = 0
        for i in range(m): count += sum(remove[i])
        answer += count
        # ์ง€์›Œ์ง„ ๋ธ”๋ก์ด ์—†์„ ๊ฒฝ์šฐ break
        if count == 0: break
        # ์ง€์›Œ์ง„ ๋ธ”๋ก์„ ์œ„์˜ ๋ธ”๋ก์œผ๋กœ ์ฑ„์šฐ๊ธฐ
        for i in range(m - 1, -1, -1):
            for j in range(n):
                if remove[i][j] == 1:
                    x = i - 1
                    while x >= 0 and remove[x][j] == 1: x -= 1
                    if x < 0:
                        board[i][j] = 0
                    else:
                        board[i][j] = board[x][j]
                        remove[x][j] = 1

    return answer

 

 

 

 

 

 

728x90