-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHamiltonian.java
More file actions
63 lines (52 loc) · 1.33 KB
/
Hamiltonian.java
File metadata and controls
63 lines (52 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
class Hamiltonian {
final int V = 5;
int path[];
boolean isSafe(int v, int graph[][], int path[], int pos){
if (graph[path[pos - 1]][v] == 0)
return false;
for (int i = 0; i < pos; i++)
if (path[i] == v)
return false;
return true;
}
boolean hamCycleUtil(int graph[][], int path[], int pos){
if (pos == V){
if (graph[path[pos - 1]][path[0]] == 1)
return true;
else
return false;
}
for (int v = 1; v < V; v++){
if (isSafe(v, graph, path, pos)){
path[pos] = v;
if (hamCycleUtil(graph, path, pos + 1))
return true;
path[pos] = -1;
}
}
return false;
}
void hamCycle(int graph[][]){
path = new int[V];
for (int i = 0; i < V; i++)
path[i] = -1;
path[0] = 0;
if (hamCycleUtil(graph, path, 1)){
System.out.println("Solution Exists: Following" + " is one Hamiltonian Cycle");
for (int i = 0; i < V; i++)
System.out.print(" " + path[i] + " ");
System.out.println(" " + path[0] + " ");
}
else
System.out.println("\nSolution does not exist");
}
public static void main(String args[]){
Hamiltonian Cycle= new Hamiltonian ();
int graph1[][] = {{0, 1, 0, 1, 0},
{1, 0, 1, 1, 1},
{0, 1, 0, 0, 1},
{1, 1, 0, 0, 1},
{0, 1, 1, 1, 0}, };
Cycle.hamCycle(graph1);
}
}