File size: 1,430 Bytes
c574d3a |
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 76 77 78 79 80 81 82 83 84 85 86 87 |
class Hamiltonian{
final int V = 5;
int path[];
boolean isSafe(int v, int graph[][], int path[], int pos)
{
// previous vertex
if(graph[path[pos-1]][v]==0)
return false;
// no duplicates are allowed
for(int i=0; i<pos; i++)
if(path[i] == v)
return false;
return true;
}
// utility for hamiltonian
boolean hcyc(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(hcyc(graph,path,pos+1) == true)
return true;
path[pos] = -1;
}
}
return false;
}
int hamcyc(int graph[][]){
path = new int[V];
for(int i=0; i<V; i++)
path[i] = -1;
path[0] = 0;
if(hcyc(graph,path,1)==false){
return 0;
}
print(path);
return 1;
}
void print(int path[]){
System.out.println("Solution ");
for(int i=0; i<V; i++){
System.out.print(path[i]+" ");
}
System.out.println(path[0]+" ");
}
public static void main(String[] args){
Hamiltonian h = 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},
};
h.hamcyc(graph1);
}
}
|