Skip to content

Commit 45f461b

Browse files
authored
Merge pull request #250 from AlgorithmStudy-Allumbus/minjeong6
Minjeong6 / 10์›” 3์ฃผ์ฐจ / 2๋ฌธ์ œ
2 parents b94a262 + 4ef3800 commit 45f461b

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
import sys
2+
from collections import deque
3+
from itertools import combinations
4+
5+
# ์ƒ, ํ•˜, ์ขŒ, ์šฐ
6+
dx = [-1, 1, 0, 0]
7+
dy = [0, 0, -1, 1]
8+
9+
input = sys.stdin.readline
10+
answer = float("inf") # ์ตœ์†Ÿ๊ฐ’์„ ์ฐพ๊ธฐ ์œ„ํ•ด ์ดˆ๊นƒ๊ฐ’์„ inf๋กœ ์„ค์ •
11+
12+
13+
def bfs(v):
14+
queue = deque(v)
15+
visited = [[-1 for _ in range(N)] for _ in range(N)]
16+
min_value = 0 # ์ตœ์†Œ ํšŸ์ˆ˜๋ฅผ ์ฐพ๊ธฐ ์œ„ํ•œ ๋ณ€์ˆ˜
17+
for x, y in queue:
18+
visited[x][y] = 0
19+
while queue:
20+
x, y = queue.popleft()
21+
for i in range(4):
22+
ax = x + dx[i]
23+
ay = y + dy[i]
24+
if 0 <= ax < N and 0 <= ay < N:
25+
if visited[ax][ay] == -1 and board[ax][ay] != 1:
26+
queue.append([ax, ay])
27+
visited[ax][ay] = visited[x][y] + 1
28+
min_value = max(min_value, visited[x][y] + 1)
29+
30+
for i in range(N):
31+
for j in range(N):
32+
if visited[i][j] == -1 and board[i][j] != 1:
33+
return float("inf")
34+
return min_value
35+
36+
37+
N, M = map(int, input().split())
38+
board = [list(map(int, input().split())) for _ in range(N)]
39+
virus = []
40+
41+
# ๋ฐ”์ด๋Ÿฌ์Šค์˜ ์ขŒํ‘œ ์ฐพ๊ธฐ
42+
for i in range(N):
43+
for j in range(N):
44+
if board[i][j] == 2:
45+
virus.append([i, j])
46+
47+
# ๋ฐ”์ด๋Ÿฌ์Šค ์ขŒํ‘œ๋“ค ์ค‘ M๊ฐœ๋ฅผ ๋ฝ‘์•„ BFS ์ˆ˜ํ–‰
48+
for v in combinations(virus, M):
49+
answer = min(bfs(v), answer)
50+
51+
# ์ •๋‹ต ๋ฐ˜ํ™˜
52+
if answer == float("inf"):
53+
print(-1)
54+
else:
55+
print(answer)
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import sys
2+
import heapq
3+
input = sys.stdin.readline
4+
5+
# ์ž…๋ ฅ
6+
N = int(input()) # ๋„์‹œ์˜ ๊ฐœ์ˆ˜
7+
M = int(input()) # ๋ฒ„์Šค์˜ ๊ฐœ์ˆ˜
8+
graph = [[] for _ in range(N+1)]
9+
for _ in range(M):
10+
start, end, weight = map(int, input().split())
11+
graph[start].append([end, weight])
12+
13+
# ์šฐ๋ฆฌ๊ฐ€ ๊ตฌํ•˜๊ณ ์ž ํ•˜๋Š” ๊ตฌ๊ฐ„์˜ ์ถœ๋ฐœ์ง€์™€ ๋„์ฐฉ์ง€ ๋ฒˆํ˜ธ
14+
goal_s, goal_e = map(int, input().split())
15+
16+
# ์ตœ๋‹จ๊ฑฐ๋ฆฌ ํ…Œ์ด๋ธ” ์ดˆ๊ธฐํ™”
17+
distances = [float('inf')] * (N+1)
18+
distances[goal_s] = 0
19+
heap = []
20+
heapq.heappush(heap, (goal_s, 0)) # ํž™(heap)์— (์‹œ์ž‘๋…ธ๋“œ, ๊ฐ€์ค‘์น˜) ์ถ”๊ฐ€
21+
22+
while heap:
23+
current, dist = heapq.heappop(heap) # ์ตœ์†Œํž™
24+
25+
if distances[current] >= dist:
26+
for node, weight in graph[current]:
27+
if dist + weight < distances[node]: # ์ง€๊ธˆ ๋ฐœ๊ฒฌํ•œ ๊ฒŒ ๋” ์ž‘์œผ๋ฉด
28+
distances[node] = dist + weight
29+
heapq.heappush(heap, (node, dist + weight))
30+
31+
print(distances[goal_e])

0 commit comments

Comments
ย (0)