Python/BFS BOJ-12100 2048 (Easy)

[Python/BFS] BOJ-12100 2048 (Easy)

πŸ“Œλ¬Έμ œλ§ν¬ 풀이참고

κΉŒλ‹€λ‘­λ‹€.

판이 μ£Όμ–΄μ§€κ³ , 각 μŠ€ν…λ§ˆλ‹€ 판 μ „μ²΄μ˜ 값이 달라진닀.

μ›€μ§μ΄λŠ” λ°©ν–₯이 4κ°€μ§€μ΄λ―€λ‘œ , λ°”λ€ŒλŠ” νŒλ„ 4κ°€μ§€λ‹€.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
from collections import deque
from copy import deepcopy

# 상 ν•˜ 쒌 우
dx = [-1,1,0,0]
dy = [0,0,-1,1]

def move(board, di):
    # 블둝이 ν•©μ³μ§ˆ 수 μžˆλŠ”μ§€λ₯Ό boolνƒ€μž…μœΌλ‘œ λ‹΄λŠ”λ‹€.
    merged = [[True]*n for _ in range(n)]
    
    # μ›€μ§μ΄λŠ” λ°©ν–₯에 따라 반볡문의 μ§„ν–‰λ°©ν–₯이 λ‹€λ₯΄λ‹€.
    # μœ„ λ˜λŠ” μ™Όμͺ½μœΌλ‘œ μ΄λ™ν•˜λŠ”κ²½μš°
    if di in [0,2]:
        start_idx, end_idx, step = 0,n,1
    # μ•„λž˜ λ˜λŠ” 였λ₯Έμͺ½μœΌλ‘œ μ΄λ™ν•˜λŠ” 경우
    else :
        start_idx, end_idx, step = n-1,-1,-1
    # ν˜„μž¬ 판의 λͺ¨λ“  μ’Œν‘œλ₯Ό νƒμƒ‰ν•˜λ©°, μ›€μ§μž„μ΄ ν•„μš”ν•œ 값듀은 움직인닀.
    for i in range(start_idx, end_idx, step):
        for j in range(start_idx, end_idx, step):
            x,y = i,j
            if board[x][y] == 0 :
                continue
            value = board[x][y]
            board[x][y] = 0
            nx, ny = x + dx[di], y + dy[di]
            while True :
                if nx < 0 or nx >=n or ny < 0 or ny >=n :
                    break # νŒμ—μ„œ 벗어남
                # λ‹€μŒ μ’Œν‘œκ°€ λΉ„μ–΄μžˆμ„ 경우, ν˜„μž¬ μ’Œν‘œλ₯Ό 이동
                if board[nx][ny] == 0 :
                    x,y = nx,ny
                    nx,ny = x + dx[di], y+dy[di]
                # λ‹€μŒ μ’Œν‘œμ™€ 같은 값인 경우, ν•˜λ‚˜μ˜ μ’Œν‘œλ‘œ ν•©μΉœλ‹€.
                elif board[nx][ny] == value and merged[nx][ny] :
                    x,y = nx,ny
                    merged[x][y] = False
                    break
                # λ‹€μŒ 이동 μ’Œν‘œκ°€ λΉ„μ–΄μžˆμ§€λ„ μ•Šκ³ , 같은 값도 μ•„λ‹Œκ²½μš° μ›€μ§μž„μ’…λ£Œ
                else :
                    break
            board[x][y] += value
    return board

def bfs(board) :
    q = deque([board])
    max_value = -1
    step = 0
    while q :
        size = len(q)
        for _ in range(size) :
            board = q.popleft()
            for di in range(4):
                next_board = move(deepcopy(board), di)
                q.append(next_board)
                
                for i in range(n):
                    for j in range(n):
                        if next_board[i][j] > max_value:
                            max_value = next_board[i][j]
        step +=1
        if step == 5 :
            return max_value

n = int(input())
board = [list(map(int,input().split())) for _ in range(n)]

print(bfs(board))

회고

이런 λ¬Έμ œλŠ” 늘 발λͺ©μ„ μž‘λŠ”λ‹€. input을 λŠ˜λ €μ„œ λ‹€μ–‘ν•œ κ°λ„λ‘œ μ ‘κ·Όν•΄λ³΄μž.