Answers for "breadth search"

2

Breadth First Search

graph = {
  '5' : ['3','7'],
  '3' : ['2', '4'],
  '7' : ['8'],
  '2' : [],
  '4' : ['8'],
  '8' : []
}

visited = [] # List for visited nodes.
queue = []     #Initialize a queue

def bfs(visited, graph, node): #function for BFS
  visited.append(node)
  queue.append(node)

  while queue:          # Creating loop to visit each node
    m = queue.pop(0) 
    print (m, end = " ") 

    for neighbour in graph[m]:
      if neighbour not in visited:
        visited.append(neighbour)
        queue.append(neighbour)

# Driver Code
print("Following is the Breadth-First Search")
bfs(visited, graph, '5')    # function calling
Posted by: Guest on March-07-2022
1

breadth first search

BFS-> uses queue
DFS-> uses stack or recursion (less code)
NOTE: same idea algo wise for both

IDEA:
1 declare the DS(if bfs-DS will be queue,if dfs-stack)
2 push the start node to DS
3 when you push you mark it as visited
4 until the DS is not empty run a loop
5 inside loop pop the DS(deque for queue or pop for stack) and save it in a new object actual
6 loop through the neighbors of actual
7 if the current neighbor n is not visited
8 then push n in DS
9 mark n as visited in the next line.
Posted by: Guest on April-21-2022

Code answers related to "breadth search"

Browse Popular Code Answers by Language