1

Problem: I need to implement a topological search using the following depth first search code.

NoteThe original code comes from here, and this is a problem given in at the end of the chapter.

I'll be honest. On a coding level, I feel pretty lost. I've added line comments to help show what I think each line is doing. While I'm fairly new to the depth first search, I understand how they work on a functional level (as opposed to my limited knowledge of their implementation). I've attempted to add the start vertices and finish times to a list so that I could then sort them later on, but I've had trouble returning that list. So that I could then sort the vertices in decreasing order of finishing time.

Note that while some solutions seem to use a stack, this code does not state the use of a stack explicitly. Rather, the stack is implicit in the recursive call to dfsvisit.

from pythonds.graphs import Graph
# Definitions
# discovery time == iterations it took for the program to find the vertex and turn it gray
# finish time == iterations it took for the program to turn the vertex black
# pred == predecessor indicator

class DFSGraph(Graph):
    def __init__(self):
        super().__init__()
        self.time = 0                       # self has an attribute 'time' (counter) that initiates at 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 print_graph(self):
        for key in sorted(list(self.vertices.keys())):
            print(key + str(self.vertices[key].neighbors + " " + str(self.vertices[key].dis)))


    def dfsvisit(self,startVertex):                     # Initiate the visit vunction of the current object (self) at the starting vertex (startVertex)
        finish_times = []                                       # Instantiate the a list to keep finish times for each node
        startVertex.setColor('gray')                    # Set the color of the starting vertex to 'gray' (discovered)
        self.time += 1                                  # Increment the timer
        startVertex.setDiscovery(self.time)             # Assign the discovery time to the current vertex (startVertex)
        for nextVertex in startVertex.getConnections(): # Begin cycling through the connected vertices (nextVertex) of startVertex
            if nextVertex.getColor() == 'white':        # If a vertex (nextVertex) with the attribute color of white is found, then do the following:
                nextVertex.setPred(startVertex)         # Set the predecessor indicator of the next vertex as the current vertex (ie if B is white and connected to A, set B's predecessor as A)
                self.dfsvisit(nextVertex)               # Recursively calls itself with the next vertex until the color of the next vertex is no longer white (i.e. all have been explored)
        startVertex.setColor('black')                   # Set the current vertice's color to black (explored)
        self.time += 1                                  # Increment the timec counter
        startVertex.setFinish(self.time)                # Assign the finish time to the current vertex (startVertex)
        finish_time = [startVertex, startVertex.setFinish(self.time)]  # append vertex and finish times to finish_time list
       return finish_time                                             # return the finish_time list

Apologies for my long comments. Hoping to understand how to implement the topological search either within this code.

alofgran
  • 427
  • 7
  • 18
  • Not clear what kind of help do you want. `Topological sorting` is a side effect of `Depth-first search`. You don't need to implement anything specifically to achieve sorting nor make any real sorting. Data is sorted at the moment when it is inserted in graph. Code you showed implements approach of traversal when visited nodes are marked instead of storing them in stack. Take a look at [comparison](https://en.wikipedia.org/wiki/Depth-first_search#Pseudocode). – cassandrad Sep 02 '19 at 15:38
  • @cassandrad - thanks for the reply. I understand that topological sorting is a potential output from depth-first searching, but that additional code is needed beyond what I've listed. So I'm looking for help writing that code within the DFS code above, and then printing out the order. I've not done that before within a class and haven't yet found a resource that's helpful to this particular case. – alofgran Sep 02 '19 at 17:05
  • As I mentioned in my writeup, the stack in the code above is _implicit_. Can the topological search not be implemented via this implicit stack (instead of an explicit one you suggest)? The link I proposed above holds documentation that seems to assure this is possible.. – alofgran Sep 02 '19 at 17:06
  • The recursive version of the psuedocode in the Wikipedia article you linked also draws on a implicit stack as well, it seems. Correct me if I'm wrong, though. – alofgran Sep 02 '19 at 17:50
  • 1
    I don't know what the `Graph` API you're extending is, so I can't directly help you with your code. But I did write a [previous answer](https://stackoverflow.com/q/47192626/1405065) about how you can transform a depth-first search into a topological sort, which might be relevant here. – Blckknght Sep 02 '19 at 23:39
  • @onhamae, you are right: top sorting can be implemented with explicit and implicit stack. So, what do you want is to help you rewrite your code to use stack explicitly? – cassandrad Sep 03 '19 at 07:53
  • @cassandrad - exactly. I have the implicit stack in my recursive DFS, but I've yet to been able to figure out how to turn that into a topological search. – alofgran Sep 03 '19 at 23:38
  • @Blckknght - I think that the end of the answer you reference is particularly pertinent (the recursive function). Working on implementing it now. I'll update this if I have any success. – alofgran Sep 05 '19 at 04:25

0 Answers0