본문 바로가기

알고리즘/백준

[Python] 백준 17837 : 새로운 게임 2

www.acmicpc.net/problem/17837

 

17837번: 새로운 게임 2

재현이는 주변을 살펴보던 중 체스판과 말을 이용해서 새로운 게임을 만들기로 했다. 새로운 게임은 크기가 N×N인 체스판에서 진행되고, 사용하는 말의 개수는 K개이다. 말은 원판모양이고, 하

www.acmicpc.net

풀이 방법

  • 칸이 흰색일 경우, 빨간색일 경우, 파란색일 경우(=범위를 넘어갈 경우)를 구분해서 각각을 구현하면 된다.
  • 빨간색일 경우 list.reverse()를 이용한다.
  • 말이 4개 이상 쌓이는 경우 바로 종료해야 하므로, 이동했을 때 바로 그 이동한 위치의 말의 개수가 몇 개인지 확인하고 4개 이상이면 종료시킨다. 

전체 코드

n, k = map(int, input().split())
board = []
for i in range(n):
    board.append(list(map(int, input().split())))
horse = []
horse_pos = [[[] for _ in range(n)] for _ in range(n)]
for i in range(k):
    r, c, d = map(int, input().split())
    horse.append([r-1, c-1, d-1])
    horse_pos[r-1][c-1].append(i)
move = [(0,1),(0,-1),(-1,0),(1,0)]
change_dir = [1,0,3,2]

for t in range(0, 1000):
    r, c = horse[0][0], horse[0][1]
    for i in range(k):
        r, c, d = horse[i]
        cr, cc = r+move[d][0], c+move[d][1]
        if (not (0<=cr<n and 0<=cc<n)) or board[cr][cc] == 2:
            horse[i][2] = change_dir[d]
            r, c, d = horse[i]
            cr, cc = r + move[d][0], c + move[d][1]
            if (not (0 <= cr < n and 0 <= cc < n)) or board[cr][cc] == 2: continue
        if board[cr][cc] == 0:
            idx = horse_pos[r][c].index(i)
            temp = horse_pos[r][c][idx:]
            for j in horse_pos[r][c][idx:]:
                horse[j][0] = cr
                horse[j][1] = cc
        elif board[cr][cc] == 1:
            idx = horse_pos[r][c].index(i)
            temp = horse_pos[r][c][idx:]
            for j in temp:
                horse[j][0] = cr
                horse[j][1] = cc
            temp.reverse()
        horse_pos[cr][cc].extend(temp)
        horse_pos[r][c] = horse_pos[r][c][:idx]
        if len(horse_pos[cr][cc]) >= 4:
            print(t+1)
            exit(0)
else:
    print(-1)
반응형