Skip to content

Commit

Permalink
2024-08-03 쉬운 최단거리
Browse files Browse the repository at this point in the history
  • Loading branch information
janghw0126 committed Aug 3, 2024
1 parent 6a452a5 commit e8fb285
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
43 changes: 43 additions & 0 deletions janghw0126/BFS/쉬운 최단거리.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import sys
from collections import deque
input = sys.stdin.readline

# 이동 방향: 상, 하, 좌, 우
directions = [(-1, 0), (1, 0), (0, -1), (0, 1)]

# 그리드의 크기 입력 받기
n, m = map(int, input().split())

# 그리드와 방문 여부 및 거리 배열 초기화
grid = [input().split() for _ in range(n)]
visited = [[False] * m for _ in range(n)]
distance = [[0] * m for _ in range(n)]

# 시작점을 찾고 BFS 초기화
for i in range(n):
for j in range(m):
if grid[i][j] == "2":
visited[i][j] = True
q = deque([(i, j)])

# BFS 탐색
while q:
x, y = q.popleft()
for dx, dy in directions:
nx = x + dx
ny = y + dy

# 그리드 범위 내에 있고, 값이 "1"이며, 아직 방문하지 않은 경우
if 0 <= nx < n and 0 <= ny < m and grid[nx][ny] == "1" and not visited[nx][ny]:
q.append((nx, ny))
visited[nx][ny] = True
distance[nx][ny] = distance[x][y] + 1

# 결과 출력
for i in range(n):
for j in range(m):
if not visited[i][j] and grid[i][j] == "1":
print(-1, end=" ") # 방문하지 않은 "1"인 경우 -1 출력
else:
print(distance[i][j], end=" ") # 거리 출력
print()
1 change: 1 addition & 0 deletions janghw0126/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,4 +36,5 @@
| 3차시 | 2024.7.24 || <a href= "https://www.acmicpc.net/problem/5430">AC</a> |[#130](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/130) |
| 4차시 | 2024.7.28 | 분할 정복 | <a href= "https://www.acmicpc.net/problem/1074">Z</a> |[#135](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/135) |
| 5차시 | 2024.7.31 | 위상정렬 | <a href= "https://www.acmicpc.net/problem/2056">작업</a> |[#138](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/138) |
| 6차시 | 2024.8.3 | BFS | <a href= "https://www.acmicpc.net/problem/14940">쉬운 최단거리</a> |[#140](https://github.com/AlgoLeadMe/AlgoLeadMe-4/pull/140) |
---

0 comments on commit e8fb285

Please sign in to comment.