Untitled

mail@pastecode.io avatar
unknown
python
2 years ago
1.6 kB
2
Indexable
Never
import sys

def FinalMT(a):
    for row in a:
        print(row)

def valid(a,hoz , ver):
    if hoz<0 or ver< 0 or hoz>=len(a) or ver>=len(a[0]): # các vị trí ngoài map
        return False
    elif a[hoz][ver] == 1: #các vị trí = 1
        return False
    return True

movement=[[0,1],[1,0],[0,-1],[-1,0],[-1,-1],[1,-1],[-1,1],[1,1]] #vector for search

def BFS(a,vis,start,end):
    #q=[[start[0],start[1]]]
    seen=[[start[0], start[1]]]
    visit=[[False for i in range(len(a[0]))] for i in range(len(a))]
    if valid(a,end[0],end[1]) == False:
        print(-1)
        return
    index=0
    d[start[0]][start[1]] = 0
    while index < len(seen):
        top = seen[index]
        for move in movement: # search 8 surround cell
            i = top[0] + move[0]
            j = top[1] + move[1]
            if valid(a, i, j) == True and visit[i][j]==False:
                d[i][j] = d[top[0]][top[1]] +1
                if i == end[0] and j == end[1]:
                    #FinalMT(d)
                    print(d[i][j])
                    return
                seen.append([i, j])
                visit[i][j]=True
                a[i][j] = 0
        index += 1
    print(-1)

inp = list(map(int,input().split()))

start, end=inp[2:4], inp[4:]
a=[]

for i in range(inp[0]):
    hor = list(map(int,input().split()))
    a.insert(0,hor)

#FinalMT(a)
#ma trận lưu khoảng cách từ gốc -> tọa độ đã đi qua
d=[[0 for i in range(inp[1])] for i in range(inp[0])]

BFS(a,d,start,end)


"""
5 5 2 0 0 3
1 1 0 0 0
0 1 1 0 0
0 0 1 1 0
0 0 0 1 1
0 0 0 0 1
"""