Question

Problem 4: Graph Traversal (25 points) Traverse the following graph, starting at vertex (node) 0, so that as each vertex is i

# 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)
                self.dfsvisit(nextVertex)
        startVertex.setColor('black')
        self.time += 1
        startVertex.setFinish(self.time)
0 0
Add a comment Improve this question Transcribed image text
Answer #1
a) BFS
Just create  list and insert nodes while traversing 

def bfs(g,start):
  start.setDistance(0)
  start.setPred(None)
  List = []
  vertQueue = Queue()
  vertQueue.enqueue(start)
  while (vertQueue.size() > 0):
    currentVert = vertQueue.dequeue()
    List.append(cuurentVert) 
    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') 
 return List

b) DFS

Just try to create a new list in dfs function and pass it as parameter to dfsvisit

def dfs(self):
        List = []
        for aVertex in self:
            aVertex.setColor('white')
            aVertex.setPred(-1)
        for aVertex in self:
            if aVertex.getColor() == 'white':
                self.dfsvisit(aVertex)
        return List

    def dfsvisit(self,startVertex,List):
        startVertex.setColor('gray')
        List.append(startVertex)
        self.time += 1
        startVertex.setDiscovery(self.time)
        for nextVertex in startVertex.getConnections():
            if nextVertex.getColor() == 'white':
                nextVertex.setPred(startVertex)
                self.dfsvisit(nextVertex,List)
        startVertex.setColor('black')
        self.time += 1
        startVertex.setFinish(self.time)
Add a comment
Know the answer?
Add Answer to:
# Problem 4 problem4_breadth_first_traversal = [0,] problem4_depth_first_traversal = [0,] def bfs(g,start): start.set...
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
  • 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

  • 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...

  • In the breadth first traversal procedure BFS, each vertex v has an attribute v.color. Modify BFS...

    In the breadth first traversal procedure BFS, each vertex v has an attribute v.color. Modify BFS so that instead of x.color, each vertex x has a Boolean attribute called x.mark, whose value is either TRUE or FALSE. The attribute x.mark must be FALSE if x has never been visited. It must be TRUE if x has been visited, but will not be visited again. Thank you!!! BFS(G, s) 1 for each vertex u e G.V-(s 11, color WHITE 4 5...

  • Previous code: class BinarySearchTree: def __init__(self, data): self.data = data self.left = None self.right = None de...

    Previous code: class BinarySearchTree: def __init__(self, data): self.data = data self.left = None self.right = None def search(self, find_data): if self.data == find_data: return self elif find_data < self.data and self.left != None: return self.left.search(find_data) elif find_data > self.data and self.right != None: return self.right.search(find_data) else: return None    def get_left(self): return self.left def get_right(self): return self.right def set_left(self, tree): self.left = tree def set_right(self, tree): self.right = tree def set_data(self, data): self.data = data def get_data(self): return self.data def traverse(root,order):...

  • Please answer all three parts. And show step-by-step answers for each part. Draw anything if necessary....

    Please answer all three parts. And show step-by-step answers for each part. Draw anything if necessary. And please don't copy other answers to be at risk being downvoted. Thank you. Question 1 (50 POINTS): Given a graph G and the Breadth First Search (BFS) and Depth First Search (DFS) traversal algorithms as follows: BFSG) 1 for each vertex u € G.V – {3} 1 2 u.color = WHITE 3 u.d = 0 4 un = NIL 3 5 S.color =...

  • The following is an adjacency matrix of a directed graph. Start from vertex D, write down...

    The following is an adjacency matrix of a directed graph. Start from vertex D, write down the order of node visited in Breadth-First- Search (BFS) traversal. (Enter the nodes in order in the following format: [A B C D E F G]) Adjacenc y Matrix ABCDEFG A 1111 000 BO00 0101 C0111010 DO 0 1 0 0 1 1 E 0 1 0 1 000 F 100 1 100 G0000100

  • # Problem 3 def printexp(tree): sVal = "" if tree: sVal = '(' + printexp(tree.getLeftChild()) sVal = sV...

    # Problem 3 def printexp(tree): sVal = "" if tree: sVal = '(' + printexp(tree.getLeftChild()) sVal = sVal + str(tree.getRootVal()) sVal = sVal + printexp(tree.getRightChild())+')' return sVal #### Functions and classes to help with Homework 6 #### You should not make any changes to the functions and classes in this file, #### but you should understand what they do and how they work. import sys ### This function will be re-defined in hw6.py. However, it is needed for ExpTree, ###...

  • (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...

  • 1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing...

    1. Code a breadth First traversal. 2. Code a depth First traversal. Note, your traversals should return a string listing the nodes added to the min spanning tree and the order they are added. Using Python. Starter code: from collections import deque class Edge: def __init__(self, endIndex, next = None): self.endIndex = endIndex self.next = next class Node: def __init__(self, name): self.name = name self.visited = False self.connects = None class Graph: def __init__(self): self.nodeList = [] self.size = 20...

  • Consider the simple graph G, given the following: (assume A=0,B=1, C=2, D=3, E=4, F=5, G=6) A...

    Consider the simple graph G, given the following: (assume A=0,B=1, C=2, D=3, E=4, F=5, G=6) A 3 3 8 B D 5 ho 5 8 E F G 4 3 a) Use the Breadth-First Search algorithm to traverse G and give the traverse sequence, starting from A. Assume you always choose the candidate with the SMALLEST index among the candidates at each step. b) Use the Depth-First Search algorithm to traverse G and give the traverse sequence, starting from A....

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
ADVERTISEMENT