[BOJ] 14940 쉬운 최단거리 Python
2023. 4. 15. 23:47ㆍ프로그래밍/문제풀이
728x90
from collections import deque
def bfs(x, y):
q = deque()
q.append([x, y])
dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]
while q:
cx, cy = q.popleft()
for i in range(4):
nx, ny = cx + dx[i], cy + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if graph[nx][ny] == -1:
graph[nx][ny] = graph[cx][cy] + 1
q.append([nx, ny])
n, m = map(int, input().split())
graph = [list(map(lambda x:x-2,map(int, input().split()))) for _ in range(n)]
for i in range(len(graph)):
for j in range(len(graph[i])):
if graph[i][j] == 0:
bfs(i, j)
break
for i in graph:
for j in i:
print(j if j != -2 else 0, end=' ')
print()
기본 bfs로 풀이하였고, 모든 조건을 만족하기 위해 그래프를 임의로 바꿨다.
입력된 수 - 2
728x90
'프로그래밍 > 문제풀이' 카테고리의 다른 글
[BOJ-1700] 멀티탭 스케줄링 Python 풀이 (0) | 2023.05.06 |
---|---|
[BOJ]1922 네트워크 연결 파이썬 풀이 (0) | 2023.04.23 |
[BOJ]2468 안전영역 파이썬 풀이 (0) | 2023.04.15 |
[BOJ] 2146 다리 만들기 Python 풀이 (0) | 2023.04.13 |
[BOJ]14395 4연산 Python 풀이 (0) | 2023.04.10 |