Determines if one of the connected components contains a cycle :return: true if one of the connected components contains a cycle :rtype: bool
(self)
| 108 | return parents |
| 109 | |
| 110 | def contains_cycle(self): |
| 111 | """ |
| 112 | Determines if one of the connected components contains a cycle |
| 113 | :return: true if one of the connected components contains a cycle |
| 114 | :rtype: bool |
| 115 | """ |
| 116 | contains_cycle = False |
| 117 | STATUS_STARTED = 1 |
| 118 | STATUS_FINISHED = 2 |
| 119 | |
| 120 | for vertex in self.get_vertex(): |
| 121 | statuses = {} |
| 122 | to_visit = [vertex] |
| 123 | |
| 124 | while to_visit and not contains_cycle: |
| 125 | v = to_visit.pop() |
| 126 | |
| 127 | if v in statuses: |
| 128 | if statuses[v] == STATUS_STARTED: |
| 129 | statuses[v] = STATUS_FINISHED |
| 130 | else: |
| 131 | statuses[v] = STATUS_STARTED |
| 132 | to_visit.append(v) # add to stack again to signal vertex has finished DFS |
| 133 | |
| 134 | for u in self.get_neighbor(v): |
| 135 | if u in statuses: |
| 136 | if statuses[u] == STATUS_STARTED: |
| 137 | contains_cycle = True |
| 138 | break |
| 139 | else: |
| 140 | to_visit.append(u) |
| 141 | |
| 142 | if contains_cycle: |
| 143 | break |
| 144 | |
| 145 | return contains_cycle |
| 146 | |
| 147 | def topological_sort(self): |
| 148 | """ |