Skip to content

Commit d229496

Browse files
authored
Create 2.py
1 parent a00cbeb commit d229496

File tree

1 file changed

+89
-0
lines changed

1 file changed

+89
-0
lines changed

19/2.py

Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
import copy
2+
3+
# 4 X 4 크기 격자에 존재하는 각 물고기의 번호(없으면 -1)와 방향 값을 담는 테이블
4+
array = [[None] * 4 for _ in range(4)]
5+
6+
for i in range(4):
7+
data = list(map(int, input().split()))
8+
# 매 줄마다 4마리의 물고기를 하나씩 확인하며
9+
for j in range(4):
10+
# 각 위치마다 [물고기의 번호, 방향]을 저장
11+
array[i][j] = [data[j * 2], data[j * 2 + 1] - 1]
12+
13+
# 8가지 방향에 대한 정의
14+
dx = [-1, -1, 0, 1, 1, 1, 0, -1]
15+
dy = [0, -1, -1, -1, 0, 1, 1, 1]
16+
17+
# 현재 위치에서 왼쪽으로 회전된 결과 반환
18+
def turn_left(direction):
19+
return (direction + 1) % 8
20+
21+
result = 0 # 최종 결과
22+
23+
# 현재 배열에서 특정한 번호의 물고기 위치 찾기
24+
def find_fish(array, index):
25+
for i in range(4):
26+
for j in range(4):
27+
if array[i][j][0] == index:
28+
return (i, j)
29+
return None
30+
31+
# 모든 물고기를 회전 및 이동시키는 함수
32+
def move_all_fishes(array, now_x, now_y):
33+
# 1번부터 16번까지의 물고기를 차례대로 (낮은 번호부터) 확인
34+
for i in range(1, 17):
35+
# 해당 물고기의 위치를 찾기
36+
position = find_fish(array, i)
37+
if position != None:
38+
x, y = position[0], position[1]
39+
direction = array[x][y][1]
40+
# 해당 물고기의 방향을 왼쪽으로 계속 회전시키며 이동이 가능한지 확인
41+
for j in range(8):
42+
nx = x + dx[direction]
43+
ny = y + dy[direction]
44+
# 해당 방향으로 이동이 가능하다면 이동 시키기
45+
if 0 <= nx and nx < 4 and 0 <= ny and ny < 4:
46+
if not (nx == now_x and ny == now_y):
47+
array[x][y][1] = direction
48+
array[x][y], array[nx][ny] = array[nx][ny], array[x][y]
49+
break
50+
direction = turn_left(direction)
51+
52+
# 상어가 현재 위치에서 먹을 수 있는 모든 물고기의 위치 반환
53+
def get_possible_positions(array, now_x, now_y):
54+
positions = []
55+
direction = array[now_x][now_y][1]
56+
# 현재의 방향으로 쭉 이동하며
57+
for i in range(4):
58+
now_x += dx[direction]
59+
now_y += dy[direction]
60+
# 범위를 벗어나지 않는지 확인하며
61+
if 0 <= now_x and now_x < 4 and 0 <= now_y and now_y < 4:
62+
# 물고기가 존재하는 경우
63+
if array[now_x][now_y][0] != -1:
64+
positions.append((now_x, now_y))
65+
return positions
66+
67+
# 모든 경우를 탐색하기 위한 DFS 함수
68+
def dfs(array, now_x, now_y, total):
69+
global result
70+
array = copy.deepcopy(array) # 리스트를 통째로 복사
71+
72+
total += array[now_x][now_y][0] # 현재 위치의 물고기 먹기
73+
array[now_x][now_y][0] = -1 # 물고기를 먹었으므로 번호 값을 -1로 변환
74+
75+
move_all_fishes(array, now_x, now_y) # 전체 물고기 이동 시키기
76+
77+
# 이제 다시 상어가 이동할 차례이므로, 이동 가능한 위치 찾기
78+
positions = get_possible_positions(array, now_x, now_y)
79+
# 이동할 수 있는 위치가 하나도 없다면 종료
80+
if len(positions) == 0:
81+
result = max(result, total) # 최댓값 저장
82+
return
83+
# 모든 이동할 수 있는 위치로 재귀적으로 수행
84+
for next_x, next_y in positions:
85+
dfs(array, next_x, next_y, total)
86+
87+
# 청소년 상어의 시작 위치(0, 0)에서부터 재귀적으로 모든 경우 탐색
88+
dfs(array, 0, 0, 0)
89+
print(result)

0 commit comments

Comments
 (0)