백준
1. 백트레킹
정해
import sys
from copy import deepcopy
input = sys.stdin.readline
dx = [-1, -1, 0, 1, 1, 1, 0, -1]
dy = [0, -1, -1, -1, 0, 1, 1, 1]
def dfs(x, y, d, cnt):
global ans, board, fish
move_fish(x, y)
while True:
nx, ny = x + dx[d], y + dy[d]
if not 0 <= nx < 4 or not 0 <= ny < 4:
ans = max(ans, cnt)
return
if not board[nx][ny]:
x, y = nx, ny
continue
temp_board, temp_fish = deepcopy(board), deepcopy(fish)
temp1, temp2 = fish[board[nx][ny][0]], board[nx][ny]
fish[board[nx][ny][0]], board[nx][ny] = [], []
dfs(nx, ny, temp2[1], cnt + temp2[0] + 1)
board, fish = temp_board, temp_fish
fish[board[nx][ny][0]], board[nx][ny] = temp1, temp2
x, y = nx, ny
def move_fish(sx, sy):
for i in range(16):
if fish[i]:
x, y = fish[i][0], fish[i][1]
for _ in range(9):
nx, ny = x + dx[board[x][y][1]], y + dy[board[x][y][1]]
if not 0 <= nx < 4 or not 0 <= ny < 4 or (nx == sx and ny == sy):
board[x][y][1] = (board[x][y][1] + 1) % 8
continue
if board[nx][ny]:
fish[board[nx][ny][0]] = [x, y]
board[nx][ny], board[x][y] = board[x][y], board[nx][ny]
fish[i] = [nx, ny]
break
board = [[] for _ in range(4)]
fish = [[] for _ in range(16)]
for i in range(4):
temp = list(map(int, input().split()))
for j in range(0, 7, 2):
board[i].append([temp[j]-1, temp[j+1]-1])
fish[temp[j]-1] = [i, j // 2]
ans = 0
d, cnt = board[0][0][1], board[0][0][0] + 1
fish[board[0][0][0]], board[0][0] = [], []
dfs(0, 0, d, cnt)
print(ans)
상어에서 막힘
from collections import defaultdict
import math
board = [[0] * 4 for _ in range(4)]
dx = [-1, -1, 0, 1, 1, 1, 0, -1]
dy = [0, -1, -1, -1, 0, 1, 1, 1]
fish = defaultdict(list)
for i in range(4):
row = list(map(int, input().split()))
for j in range(0, 7, 2):
fish[row[j]] = [i, j // 2, row[j + 1] - 1]
board[i][j // 2] = [row[j], row[j + 1] - 1]
while True:
for i in range(1, 17):
if i in ate:
continue
x, y, d = fish[i]
for _ in range(8):
nx, ny = x + dx[d], y + dy[d]
if 0 <= nx < 4 and 0 <= ny < 4 and board[nx][ny] != 2 :
if board[nx][ny] == 0:
board[x][y] = 0
board[nx][ny] = board[x][y]
break
else:
num, dir = board[nx][ny]
board[x][y], board[nx][ny] = board[nx][ny], board[x][y]
fish[i] = [nx, ny, d]
fish[num] = [x, y, dir]
break
else:
d = d + 1 % 8
can = []
nsx, nsy = sx, sy
while nsx < 4 and nsy < 4:
nsx = nsx + dx[sd]
nsy = nsy + dy[sd]
if 0 <= nsx < 4 and 0 <= nsy < 4 and board[nx][ny] != 0:
can.append([nsx, nsy])
print(can)