1

This is a BFS code using Queue G1:vertex from collections import deque and I want to implement DFS and UCS code from this BFS code using stack instead of queue. Please help me with this code.


graph={ 'a': set(['b','c']),
        'b': set(['a','d']),
        'c': set(['a','d','f']),
        'd': set(['b','c','e','s']),
        'e': set(['d','h','s','r']),
        'f': set(['G','c','r']),
        'G': set(['f']),
        'h': set(['e','p','q']),
        'p': set(['s','q','h']),
        'q': set(['p','h']),
        'r': set(['e','f']),
        's': set(['d','e','p'])}

def bfs(graph, start,goal):
    visited= []
    path=[]
    queue=deque([start])

    while queue:
        vertex= queue.popleft()

        if vertex not in path:        
           path.extend(vertex)
           visited.extend(vertex)
           queue.extend(list(set(graph[vertex])))
        if goal in path:
            return (path,visited)
        checker=1
        for a in graph:
            for b in graph[a]:
                if b in path:
                    checker=(checker)*(1)
                else:
                     checker=(checker)*(0)
            if(checker>0):
                if a not in visited:
                    visited.extend(a)
    return (path,visited)
p=[]
p.extend(bfs(graph,'s','G'))
print("path :",p[0])
print("visited nodes:",p[1])

c0der
  • 18,467
  • 6
  • 33
  • 65
  • DFS is a distributed filesystem from Microsoft. Note: for questions about depth-first search, please use the depth-first-search tag. **NOT to be confused** with [depth-first-search] – c0der Apr 21 '20 at 04:20

1 Answers1

0

Replace

queue=deque([start])

with

queue=[start] # just a list

And

vertex = queue.popleft()

with

vertex= queue.pop(-1) # like a stack, pop the last item from the list

The output becomes:

path : ['s', 'd', 'b', 'a', 'c', 'f', 'r', 'e', 'h', 'p', 'q', 'G']
visited nodes: ['s', 'd', 'b', 'a', 'c', 'f', 'r', 'e', 'h', 'p', 'q', 'G']
rdas
  • 20,604
  • 6
  • 33
  • 46