forked from infiniteoverflow/VTU-DAA-LAB
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHamiltonian.java
75 lines (62 loc) · 1.79 KB
/
Hamiltonian.java
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
64
65
66
67
68
69
70
71
72
73
74
75
package com.programs;
public 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;
}
int 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)) {
return 0;
}
printSolution(path);
return 1;
}
public void printSolution(int path[]) {
System.out.println("Solution exists:\n Following is one Hamiltonian Cycle:");
for(int i=0;i<V;i++)
System.out.print(" "+path[i]+" ");
System.out.println(" "+path[0]);
}
public static void main(String[] args) {
Hamiltonian hamiltonian = 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}};
hamiltonian.hamCycle(graph1);
int graph2[][] = {{0,1,0,1,0},
{1,0,1,1,1},
{0,1,0,0,1},
{1,1,0,0,0},
{0,1,1,0,0}};
hamiltonian.hamCycle(graph2);
}
}