Subscribe Us

Responsive Advertisement

Advertisement

Samile maze using BFS | Python Code

 


from collections import deque
adj={
    'S':['A','B','D','E'],
    'A':['S'],
    'B':['S','C','D'],
    'C':['B','J'],
    'D':['B','G','S'],
    'E':['G','S'],
    'F':['G','H'],
    'G':['D','E','F','J','H'],
    'H':['G','F','I'],
    'I':['H','J'],
    'J':['I','C','G']

}
def bfs(start,end):
    q=deque([(start,[start])])
    vis=set()
    vis.add(start)
    while q:
        node,path=q.popleft()
        if node==end:
            return path
        for child in adj[node]:
         
            if child not in vis:
                q.append((child,path+[child]))
                vis.add(child)
    return None
start="S"
end="I"

print("BFS solution : ")
print(bfs(start,end))

Post a Comment

0 Comments