|
| 1 | + |
| 2 | +class Graph(): |
| 3 | + def __init__(self, vertices): |
| 4 | + self.graph = [[0 for column in range(vertices)]\ |
| 5 | + for row in range(vertices)] |
| 6 | + self.V = vertices |
| 7 | + |
| 8 | + def isSafe(self, v, pos, path): |
| 9 | + # Check if current vertex and last vertex |
| 10 | + # in path are adjacent |
| 11 | + if self.graph[ path[pos-1] ][v] == 0: |
| 12 | + return False |
| 13 | + |
| 14 | + # Check if current vertex not already in path |
| 15 | + for vertex in path: |
| 16 | + if vertex == v: |
| 17 | + return False |
| 18 | + |
| 19 | + return True |
| 20 | + |
| 21 | + def hamCycleUtil(self, path, pos): |
| 22 | + |
| 23 | + # base case: if all vertices are |
| 24 | + # included in the path |
| 25 | + if pos == self.V: |
| 26 | + # Last vertex must be adjacent to the |
| 27 | + # first vertex in path to make a cyle |
| 28 | + if self.graph[ path[pos-1] ][ path[0] ] == 1: |
| 29 | + return True |
| 30 | + else: |
| 31 | + return False |
| 32 | + |
| 33 | + for v in range(1,self.V): |
| 34 | + |
| 35 | + if self.isSafe(v, pos, path) == True: |
| 36 | + |
| 37 | + path[pos] = v |
| 38 | + |
| 39 | + if self.hamCycleUtil(path, pos+1) == True: |
| 40 | + return True |
| 41 | + |
| 42 | + # Remove current vertex if it doesn't |
| 43 | + # lead to a solution |
| 44 | + path[pos] = -1 |
| 45 | + |
| 46 | + return False |
| 47 | + |
| 48 | + def hamCycle(self): |
| 49 | + path = [-1] * self.V |
| 50 | + |
| 51 | + ''' Let us put vertex 0 as the first vertex |
| 52 | + in the path. If there is a Hamiltonian Cycle, |
| 53 | + then the path can be started from any point |
| 54 | + of the cycle as the graph is undirected ''' |
| 55 | + path[0] = 0 |
| 56 | + |
| 57 | + if self.hamCycleUtil(path,1) == False: |
| 58 | + print "Solution does not exist\n" |
| 59 | + return False |
| 60 | + |
| 61 | + self.printSolution(path) |
| 62 | + return True |
| 63 | + |
| 64 | + def printSolution(self, path): |
| 65 | + print "Solution Exists: Following is one Hamiltonian Cycle" |
| 66 | + for vertex in path: |
| 67 | + print vertex, |
| 68 | + print path[0], "\n" |
| 69 | + |
| 70 | +''' Let us create the following graph |
| 71 | + (0)--(1)--(2) |
| 72 | + | / \ | |
| 73 | + | / \ | |
| 74 | + | / \ | |
| 75 | + (3)-------(4) ''' |
| 76 | +g1 = Graph(5) |
| 77 | +g1.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], |
| 78 | + [0, 1, 0, 0, 1,],[1, 1, 0, 0, 1], |
| 79 | + [0, 1, 1, 1, 0], ] |
| 80 | + |
| 81 | +# Print the solution |
| 82 | +g1.hamCycle(); |
| 83 | + |
| 84 | +''' Let us create the following graph |
| 85 | + (0)--(1)--(2) |
| 86 | + | / \ | |
| 87 | + | / \ | |
| 88 | + | / \ | |
| 89 | + (3) (4) ''' |
| 90 | +g2 = Graph(5) |
| 91 | +g2.graph = [ [0, 1, 0, 1, 0], [1, 0, 1, 1, 1], |
| 92 | + [0, 1, 0, 0, 1,], [1, 1, 0, 0, 0], |
| 93 | + [0, 1, 1, 0, 0], ] |
| 94 | + |
| 95 | +# Print the solution |
| 96 | +g2.hamCycle(); |
0 commit comments