Study/코딩테스트 연습
프로그래머스 dfs/bfs 게임 맵 최단거리 파이썬
soyeonland
2024. 10. 13. 14:50
실수한것
더보기
maps 를 map 이라고 오타내서 문제 (map이라는 함수가 있기 때문에)
cur_cnt 를 처음부터 고려하지 않은것?
from collections import deque
def solution(maps):
answer = 100000
row = len(maps)
col = len(maps[0])
visited = [[False]*col for _ in range(row)]
# print('visited',visited)
dx=[-1,1,0,0]
dy=[0,0,-1,1]
q = deque()
def bfs():
nonlocal answer
start = [0,0,1]
q.append(start)
visited[start[0]][start[1]]=True
#print('start',start,'q',q, 'len(q)', len(q))
while(len(q)>=1):
cur_x, cur_y, cur_cnt = q.popleft()
#print('cur_x', cur_x, 'cur_y',cur_y,'cur_cnt',cur_cnt)
for d in range(4):
new_x = cur_x + dx[d]
new_y = cur_y + dy[d]
#print('new_x', new_x, 'new_y',new_y)
if new_x<0 or new_x >=row or new_y<0 or new_y>=col:
continue
if maps[new_x][new_y]==0:
continue
if visited[new_x][new_y]==True:
continue
if new_x == row-1 and new_y == col-1:
# print('answer',answer)
answer = min(answer, cur_cnt + 1)
continue
q.append([new_x, new_y, cur_cnt + 1])
visited[new_x][new_y] = 1
bfs()
if answer==100000:
answer = -1
return answer