[틀린문제찾기] 미로찾기
2022. 4. 23. 22:48ㆍ알고리즘(Python)
<1차 풀이>
from collections import deque
import math
from sys import stdin
n,m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
#이동할 벡터(상,하,좌,우)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
q = deque()
q.append((x, y))
while q:
x, y = q.popleft()
#4방향을 체크
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
#해당되지 않는 범위 체크
if 0 <= nx < n and 0 <= ny < m:
if not graph[nx][ny] == 0:
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
q.append((nx, ny))
return graph[n-1][m-1]
print(bfs(0,0))
<정답 풀이>
from collections import deque
import math
from sys import stdin
n,m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
#이동할 벡터(상,하,좌,우)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
q = deque()
q.append((x, y))
while q:
x, y = q.popleft()
#4방향을 체크
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
#해당되지 않는 범위 체크
if nx < 0 or ny < 0 or nx >= n or ny >= m:
continue
if graph[nx][ny] == 0:
continue
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
q.append((nx, ny))
return graph[n-1][m-1]
print(bfs(0,0))
<수정한 풀이>
from collections import deque
import math
from sys import stdin
n,m = map(int, input().split())
graph = []
for i in range(n):
graph.append(list(map(int, input())))
#이동할 벡터(상,하,좌,우)
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
def bfs(x, y):
q = deque()
q.append((x, y))
while q:
x, y = q.popleft()
#4방향을 체크
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
#해당되지 않는 범위 체크
if 0 <= nx < n and 0 <= ny < m:
if not graph[nx][ny] == 0:
if graph[nx][ny] == 1:
graph[nx][ny] = graph[x][y] + 1
q.append((nx, ny))
return graph[n-1][m-1]
print(bfs(0,0))
'알고리즘(Python)' 카테고리의 다른 글
[백준] 1296. 팀 이름 정하기 (0) | 2022.04.08 |
---|