BFS 문제풀이 최단거리 찾기

이렇게 짤거면 뭐하러 파이썬 쓰는걸까 희희
나가 뒤지자

shortest.in
5
1 1 1 0 0
0 0 1 1 1
1 1 1 0 1
1 0 0 0 1
1 1 1 1 1
----------

def read_file(file_name):
    result = []
    with open(file_name, 'r') as f:
        lines = f.readlines()
        for l in lines:
            result.append([int(e) for e in l.split()])
    return result
tups = read_file("shortest.in")
my_map = tups[1:]
start = (0,0)
end = (len(my_map)-1, len(my_map[0])-1)
my_que = []

def BFS(start_point):
    my_que.append((start_point,0))
    while my_que and my_que[0][0] != end:
        now_point, now_len = my_que.pop(0)
        my_map[now_point[0]][now_point[1]] = 0        if now_point[1]+1 < len(my_map[0]) and my_map[now_point[0]][now_point[1]+1]==1:
            my_que.append(((now_point[0], now_point[1]+1), now_len+1))
        if now_point[1]-1 >= 0 and my_map[now_point[0]][now_point[1]-1]==1:
            my_que.append(((now_point[0], now_point[1]-1), now_len+1))
        if now_point[0]+1 < len(my_map) and my_map[now_point[0]+1][now_point[1]]==1:
            my_que.append(((now_point[0]+1, now_point[1]), now_len+1))
        if now_point[0]-1 >= 0 and my_map[now_point[0]-1][now_point[1]]==1:
            my_que.append(((now_point[0]-1, now_point[1]), now_len+1))
    if my_que:
        return my_que[0][1]
    return -1
L=BFS(start)
print(L)

댓글

가장 많이 본 글