보물창고 블로그

백준 알고리즘 새로운 게임2 풀이 With Python 본문

알고리즘 풀이/백준 알고리즘

백준 알고리즘 새로운 게임2 풀이 With Python

홋 메 2020. 3. 10. 16:09
728x90

문제 링크: https://www.acmicpc.net/problem/17837

 

17837번: 새로운 게임 2

재현이는 주변을 살펴보던 중 체스판과 말을 이용해서 새로운 게임을 만들기로 했다. 새로운 게임은 크기가 N×N인 체스판에서 진행되고, 사용하는 말의 개수는 K개이다. 말은 원판모양이고, 하나의 말 위에 다른 말을 올릴 수 있다. 체스판의 각 칸은 흰색, 빨간색, 파란색 중 하나로 색칠되어있다. 게임은 체스판 위에 말 K개를 놓고 시작한다. 말은 1번부터 K번까지 번호가 매겨져 있고, 이동 방향도 미리 정해져 있다. 이동 방향은 위, 아래, 왼쪽, 오른쪽

www.acmicpc.net

문제는 아래와 같습니다.

이번 문제는 위에 쌓는 것을 어떻게 구현하는가의 문제였다. 나는 리스트를 통해서 쌓는 것을 구현하였다. 코드는 아래와 같다. 

import sys


def solution(map1, map2, horses):
    t = 1
    while 1:
        if t > 1000:
            return -1
        for i in range(k):
            x, y, d = horses[i]
            nx = x + dx[d]
            ny = y + dy[d]
            # 파란색이거나 영역밖이면
            if not (-1 < nx < n and -1 < ny < n) or map1[nx][ny] == 2:
                d ^= 1
                nx = x + dx[d]
                ny = y + dy[d]
                if not (-1 < nx < n and -1 < ny < n) or map1[nx][ny] == 2:
                    nx = x
                    ny = y
            horses[i] = [nx, ny, d]
            if nx == x and ny == y:
                continue
            # 옮긴 뒤의 색이 하얀색
            idx = map2[x][y].index(i)
            for p in map2[x][y][idx + 1:]:
                horses[p][0] = nx
                horses[p][1] = ny
            if map1[nx][ny] == 0:
                map2[nx][ny] += map2[x][y][idx:]
            # 옮긴 뒤에 색이 빨간색
            elif map1[nx][ny] == 1:
                map2[nx][ny] += map2[x][y][idx:][::-1]
            map2[x][y] = map2[x][y][:idx]
            if len(map2[nx][ny]) > 3:
                return t
        t += 1


dx = [0, 0, -1, 1]
dy = [1, -1, 0, 0]
n, k = map(int, sys.stdin.readline().split())
map1 = [list(map(int, sys.stdin.readline().split())) for _ in range(n)]
horses = []
map2 = [[[] * n for _ in range(n)] for _ in range(n)]
for i in range(k):
    x, y, d = map(int, sys.stdin.readline().split())
    horses.append([x - 1, y - 1, d - 1])
    map2[x - 1][y - 1].append(i)
ans=solution(map1,map2,horses)
print(ans)
Comments