Advertisement
Guest User

Untitled

a guest
Nov 10th, 2018
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.09 KB | None | 0 0
  1. # this is template code for graph and DFS
  2.  
  3. class Graph:
  4.    def __init__(self, G):
  5.       '''
  6.          G is a dictionary of adjacency list that maps each vertex u (string)
  7.          to a list of vertices v (so (u, v) is an edge)
  8.      '''
  9.       self.G = G
  10.       self.vertices = list(G.keys())
  11.  
  12.    def Adj(self, v):
  13.       '''iterator for the adjacency list'''
  14.       for i in self.G[v]:
  15.          yield i
  16.  
  17.    def V(self):
  18.       '''iterator for the vertices'''
  19.       for i in self.vertices:
  20.          yield i
  21.  
  22.    def findCycle(self):
  23.       '''
  24.         return a list of vertice that form a cycle
  25.      '''
  26.       return DFS(self)
  27.  
  28.  
  29. ### Code for DFS ###
  30. WHITE = 'white'
  31. GRAY =  'gray'
  32. BLACK = 'black'
  33.  
  34.  
  35. def DFS(G):
  36.    G.color = {} # color, which is WHITE, GRAY, or BLACK
  37.    G.pred = {}  # the predecessor
  38.    # you may add your own field for tracking cycles
  39.    G.cycle = []
  40.  
  41.    for u in G.V():
  42.       G.color[u] = WHITE
  43.       G.pred[u] = None
  44.    for u in G.V():
  45.       if G.color[u] == WHITE:
  46.          DFSVisit(G, u)
  47.  
  48. def DFSVisit(G, u):
  49.    G.color[u] = GRAY
  50.    for v in G.Adj(u):
  51.       if G.color[v] == WHITE:
  52.          G.pred[v] = u
  53.          DFSVisit(G, v)
  54.       # add your own code for cycle detection
  55.       elif G.color[v] == GRAY:
  56.           G.cycle.append(v)
  57.           G.cycle.append(u)
  58.           while u in G.pred and G.pred[u] != v:
  59.               u = G.pred[u]
  60.               G.cycle.append(u)
  61.           G.cycle.append(v)
  62.           G.cycle.reverse()
  63.           print("*****")
  64.           print(G.cycle)
  65.           print("*****")
  66.           return G.cycle
  67.    G.color[u] = BLACK
  68.  
  69. # our test case. Define a dictionary of adjacency lists for each vertex.
  70.  
  71. if __name__ == '__main__':
  72.    L = [
  73.         {'P1':['R1'], 'P2':['R3', 'R4', 'R5'], 'P3': ['R5'], 'P4': ['R2'],
  74.          'P5': [], 'R1':['P2'], 'R2': ['P1'], 'R3': ['P5'], 'R4': ['P3'],
  75.          'R5': ['P4'] },
  76.         {'P1': ['P2'], 'P2': ['P3', 'P4', 'P5'], 'P3':['P4'],
  77.          'P4': ['P1'], 'P5': [] }\
  78.         ]
  79.  
  80.    for g in map(Graph, L):
  81.       print('g=%s, cycle=%s' % (g.G, g.findCycle()))
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement