Question

Given breadth first search function as below. Write a bfs_new(a_tree, start, goal), which does the following....

Given breadth first search function as below. Write a bfs_new(a_tree, start, goal), which does the following. We store one additional dictionary variable, called parent, to store the parent of each node. In the beginning, set parent = { start: 'NOBODY'}. Each time that a node is expanded, we add one entry in parent for each of its children. The input goal is the name of a node; if bfs_new reaches the node called goal, then the search is terminated, and the program should print out the path from the goal node to the start node, by using the data stored in parent.

def bfs_tree(a_tree, start):

open_nodes = [start]

path = []

while len(open_nodes) > 0:

vertex = open_nodes.pop(0)​# pop(0) deletes and returns the first item

if vertex in path:

continue

path.append(vertex)​​# append adds element to end of path

for neighbor in a_tree[vertex]:

open_nodes.append(neighbor)

return path

0 0
Add a comment Improve this question Transcribed image text
Answer #1

bfs_new:

def bfs_new(atree, start,goal):

               open_nodes = [start]

               path = []

               parent = {start: 'NOBODY}             #parent dictionary

               while len(open_nodes)>0 and vertex!=goal:  #loops till goal isnt reached

                              vertex = open_nodes.pop(0)

                              if vertex not in path: #if vertex is never explored

                                             path.append(vertex)

                                             for neighbor in open_nodes[vertex]:

                                                            path.append(vertex)

                                                            if neighbor not in parent:               #if neighbour is not explored

                                                                           parent[neighbor] = vertex     #set vertex as parent of neighbor

                                                           

Add a comment
Know the answer?
Add Answer to:
Given breadth first search function as below. Write a bfs_new(a_tree, start, goal), which does the following....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Minimum Spanning Trees Networks & Graphs 1. Create a spanning tree using the breadth-first search algorithm....

    Minimum Spanning Trees Networks & Graphs 1. Create a spanning tree using the breadth-first search algorithm. Start at A (i..0) and label cach vertex with the correct number after A and show your path. How many edges were used to create a spanning tree? 2. Create a spanning tree using the breadth-first search algorithm. Start at G (ie. O) and label each vertex with the correct number after A and show your path How many edges were used to create...

  • Question 3 1 pts Select all of the following that are true: Breadth-First Search only adds...

    Question 3 1 pts Select all of the following that are true: Breadth-First Search only adds each vertex to the queue once. Breadth-First Search generally uses more space compared to Depth-First search. Breadth-First Search may not find the shortest path for an unweighted graph if the graph contains a cycle. At any time during Breadth-First Search, the queue holds at most two distinct dist values from all vertices in

  • In Python 3 please Apply Breadth First Search (BFS) to traverse the following graph. Start your...

    In Python 3 please Apply Breadth First Search (BFS) to traverse the following graph. Start your traversal from vertex 0, and write down the order in which vertices will be visited during the traversal. 1 8 6 7 2 9 5 4 3

  • (5 marks) a. The pseudo-code for breadth-first search, modified slightly from Drozdek,1 is as follows: void...

    (5 marks) a. The pseudo-code for breadth-first search, modified slightly from Drozdek,1 is as follows: void breadthFirstSearch (vertex w) for all vertices u num (u) 0 null edges i=1; num (w) i++ enqueue (w) while queue is not empty dequeue ( V= for all vertices u adjacent to v if num(u) is 0 num (u) = i++; enqueue (u) attach edge (vu) to edges; output edges; Now consider the following graph. Give the breadth-first traversal of the graph, starting from...

  • from collections import defaultdict    # This class represents a directed graph using # adjacency list...

    from collections import defaultdict    # This class represents a directed graph using # adjacency list representation class Graph:        # Constructor     def __init__(self):            # default dictionary to store graph         self.graph = defaultdict(list)        # function to add an edge to graph     def addEdge(self,u,v):         self.graph[u].append(v)        # Function to print a BFS of graph     def BFS(self, s):            # Mark all the vertices as not visited         visited = [False] * (len(self.graph))            # Create a queue for BFS         queue...

  • # Problem 4 problem4_breadth_first_traversal = [0,] problem4_depth_first_traversal = [0,] def bfs(g,start): start.set...

    # Problem 4 problem4_breadth_first_traversal = [0,] problem4_depth_first_traversal = [0,] def bfs(g,start): start.setDistance(0) start.setPred(None) vertQueue = Queue() vertQueue.enqueue(start) while (vertQueue.size() > 0): currentVert = vertQueue.dequeue() for nbr in currentVert.getConnections(): if (nbr.getColor() == 'white'): nbr.setColor('gray') nbr.setDistance(currentVert.getDistance() + 1) nbr.setPred(currentVert) vertQueue.enqueue(nbr) currentVert.setColor('black') class DFSGraph(Graph): def __init__(self): super().__init__() self.time = 0 def dfs(self): for aVertex in self: aVertex.setColor('white') aVertex.setPred(-1) for aVertex in self: if aVertex.getColor() == 'white': self.dfsvisit(aVertex) def dfsvisit(self,startVertex): startVertex.setColor('gray') self.time += 1 startVertex.setDiscovery(self.time) for nextVertex in startVertex.getConnections(): if nextVertex.getColor() == 'white': nextVertex.setPred(startVertex)...

  • (c) Simulate breadth first search on the graph shown in Fig HW2Q1c. You can assume that...

    (c) Simulate breadth first search on the graph shown in Fig HW2Q1c. You can assume that the starting vertex is 1, and the neighbors of a vertex are examined in increasing numerical order (i.e. if there is a choice between two or more neighbors, we pick the smaller one). You have to show: both the order in which the vertices are visited and the breadth first search tree. No explanations necessary. (d) On the same graph, i.e. the graph in...

  • and the arrows represent possible action transitions. S is the start state and there are two goal states: G1 and G1. The cost of each action is given by the number next to the arrow. Each state is la...

    and the arrows represent possible action transitions. S is the start state and there are two goal states: G1 and G1. The cost of each action is given by the number next to the arrow. Each state is labelled by an identifying name (S, A-F, G1, G2, H) and also a number. The number is the value of a heuristic function, which gives an estimate of the cost of getting to the nearest goal from that node. (a) Consider the...

  • You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a...

    You will be implementing a Breadth-First Search (BFS) and a Depth-First Search (DFS) algorithm on a graph stored as an adjacency list. The AdjacencyList class inherits from the Graph class shown below. class Graph { private: vector _distances; vector _previous; public: Graph() { } virtual int vertices() const = 0; virtual int edges() const = 0; virtual int distance(int) const = 0; virtual void bfs(int) const = 0; virtual void dfs(int) const = 0; virtual void display() const = 0;...

  • Write a function which performs Breadth First Search on the given graph. Also write in which order the nodes are visited. Class Node { public int value; public Node[] neighbors; public boolean visite...

    Write a function which performs Breadth First Search on the given graph. Also write in which order the nodes are visited. Class Node { public int value; public Node[] neighbors; public boolean visited; public Node(int num) { neighbors = new Node[5]; visited = False; data = num } } 40 20 50 70 10 30 60 40 20 50 70 10 30 60

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT