forked from 2ByungJun/python-for-coding-test
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1.py
More file actions
83 lines (74 loc) ยท 2.78 KB
/
1.py
File metadata and controls
83 lines (74 loc) ยท 2.78 KB
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
71
72
73
74
75
76
77
78
79
80
81
82
83
from collections import deque
INF = 1e9 # ๋ฌดํ์ ์๋ฏธํ๋ ๊ฐ์ผ๋ก 10์ต์ ์ค์
# ๋งต์ ํฌ๊ธฐ N ์
๋ ฅ
n = int(input())
# ์ ์ฒด ๋ชจ๋ ์นธ์ ๋ํ ์ ๋ณด ์
๋ ฅ
array = []
for i in range(n):
array.append(list(map(int, input().split())))
# ์๊ธฐ ์์ด์ ํ์ฌ ํฌ๊ธฐ ๋ณ์์ ํ์ฌ ์์น ๋ณ์
now_size = 2
now_x, now_y = 0, 0
# ์๊ธฐ ์์ด์ ์์ ์์น๋ฅผ ์ฐพ์ ๋ค์ ๊ทธ ์์น์ ์๋ฌด๊ฒ๋ ์๋ค๊ณ ์ฒ๋ฆฌ
for i in range(n):
for j in range(n):
if array[i][j] == 9:
now_x, now_y = i, j
array[now_x][now_y] = 0
dx = [-1, 0, 1, 0]
dy = [0, 1, 0, -1]
# ๋ชจ๋ ์์น๊น์ง์ '์ต๋จ ๊ฑฐ๋ฆฌ๋ง' ๊ณ์ฐํ๋ BFS ํจ์
def bfs():
# ๊ฐ์ด -1์ด๋ผ๋ฉด ๋๋ฌํ ์ ์๋ค๋ ์๋ฏธ (์ด๊ธฐํ)
dist = [[-1] * n for _ in range(n)]
# ์์ ์์น๋ ๋๋ฌ์ด ๊ฐ๋ฅํ๋ค๊ณ ๋ณด๋ฉฐ ๊ฑฐ๋ฆฌ๋ 0
q = deque([(now_x, now_y)])
dist[now_x][now_y] = 0
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx and nx < n and 0 <= ny and ny < n:
# ์์ ์ ํฌ๊ธฐ๋ณด๋ค ์๊ฑฐ๋ ๊ฐ์ ๊ฒฝ์ฐ์ ์ง๋๊ฐ ์ ์์
if dist[nx][ny] == -1 and array[nx][ny] <= now_size:
dist[nx][ny] = dist[x][y] + 1
q.append((nx, ny))
# ๋ชจ๋ ์์น๊น์ง์ ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ ๋ฐํ
return dist
# ์ต๋จ ๊ฑฐ๋ฆฌ ํ
์ด๋ธ์ด ์ฃผ์ด์ก์ ๋, ๋จน์ ๋ฌผ๊ณ ๊ธฐ๋ฅผ ์ฐพ๋ ํจ์
def find(dist):
x, y = 0, 0
min_dist = INF
for i in range(n):
for j in range(n):
# ๋๋ฌ์ด ๊ฐ๋ฅํ๋ฉด์ ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ์ผ ๋
if dist[i][j] != -1 and 1 <= array[i][j] and array[i][j] < now_size:
# ๊ฐ์ฅ ๊ฐ๊น์ด ๋ฌผ๊ณ ๊ธฐ ํ ๋ง๋ฆฌ๋ง ์ ํ
if dist[i][j] < min_dist:
x, y = i, j
min_dist = dist[i][j]
if min_dist == INF: # ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ๊ฐ ์๋ ๊ฒฝ์ฐ
return None
else:
return x, y, min_dist # ๋จน์ ๋ฌผ๊ณ ๊ธฐ์ ์์น์ ์ต๋จ ๊ฑฐ๋ฆฌ
result = 0 # ์ต์ข
๋ต์
ate = 0 # ํ์ฌ ํฌ๊ธฐ์์ ๋จน์ ์
while True:
# ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ์ ์์น ์ฐพ๊ธฐ
value = find(bfs())
# ๋จน์ ์ ์๋ ๋ฌผ๊ณ ๊ธฐ๊ฐ ์๋ ๊ฒฝ์ฐ, ํ์ฌ๊น์ง ์์ง์ธ ๊ฑฐ๋ฆฌ ์ถ๋ ฅ
if value == None:
print(result)
break
else:
# ํ์ฌ ์์น ๊ฐฑ์ ๋ฐ ์ด๋ ๊ฑฐ๋ฆฌ ๋ณ๊ฒฝ
now_x, now_y = value[0], value[1]
result += value[2]
# ๋จน์ ์์น์๋ ์ด์ ์๋ฌด๊ฒ๋ ์๋๋ก ์ฒ๋ฆฌ
array[now_x][now_y] = 0
ate += 1
# ์์ ์ ํ์ฌ ํฌ๊ธฐ ์ด์์ผ๋ก ๋จน์ ๊ฒฝ์ฐ, ํฌ๊ธฐ ์ฆ๊ฐ
if ate >= now_size:
now_size += 1
ate = 0