Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit12b38cf

Browse files
authored
Merge pull request#8 from sandeepsj/Hamiltonean-Cycles
Add Hamiltonean cycles
2 parentsf4e5f4f +3ed3d80 commit12b38cf

File tree

1 file changed

+102
-0
lines changed

1 file changed

+102
-0
lines changed
Lines changed: 102 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,102 @@
1+
//A Hamiltonian cycle is a cycle in an undirected or directed graph that visits each vertex exactly once.
2+
// import visualization libraries {
3+
importorg.algorithm_visualizer.*;
4+
importjava.util.Random;
5+
// }
6+
7+
classMain {
8+
// define tracer variables {
9+
GraphTracergraphTracer=newGraphTracer("GraphTracer");
10+
LogTracerlogTracer =newLogTracer("Console");
11+
// }
12+
intn=8;
13+
intx[];
14+
intfound=0;
15+
intvis[];
16+
int[][]adjacencyMatrix;
17+
voidham(intk) {
18+
while(true)
19+
{
20+
nextVal(k);
21+
if(x[k]==-1)
22+
return;
23+
if(k==n-1)
24+
{
25+
graphTracer.visit(x[0],x[k]);
26+
graphTracer.delay();
27+
found=1;
28+
//Printint the cycle{
29+
for(inti=0;i<n;i++)
30+
logTracer.print((x[i])+" ");
31+
logTracer.println(0);
32+
//}
33+
graphTracer.leave(x[0],x[k]);
34+
}
35+
else
36+
ham(k+1);
37+
}
38+
}
39+
voidnextVal(intk)
40+
{
41+
while(true) {
42+
inti=0;
43+
if(vis[k]==1)
44+
graphTracer.leave(x[k],x[k-1]);
45+
vis[k]=0;
46+
x[k]=(x[k]+1)%(n+1);
47+
if(x[k]==n)
48+
{
49+
x[k]=-1;
50+
return;
51+
}
52+
graphTracer.visit(x[k],x[k-1]);
53+
graphTracer.delay();
54+
vis[k]=1;
55+
if (adjacencyMatrix[x[k-1]][x[k]]==1)
56+
{
57+
for(i=0;i<k;i++)
58+
if(x[i]==x[k])
59+
break;
60+
if(i==k)
61+
if(k<n-1 ||k==n-1 &&adjacencyMatrix[x[k]][x[0]]==1)
62+
return;
63+
}
64+
}
65+
}
66+
67+
Main() {
68+
//initializing{
69+
adjacencyMatrix=newint[n][n];
70+
x=newint[n];
71+
vis=newint[n];
72+
Randomr=newRandom();
73+
for(inti=1;i<n;i++)
74+
x[i]=-1;
75+
//}
76+
77+
//Randomizing adjacancy matrix and displaying on log screen{
78+
logTracer.println("The adjacancy Matrix is");
79+
for(inti=0;i<n;i++){
80+
for(intj=0;j<n;j++){
81+
adjacencyMatrix[i][j]=r.nextInt(2);
82+
logTracer.print(adjacencyMatrix[i][j]+" ");
83+
}
84+
logTracer.println("");
85+
}
86+
//}
87+
88+
// visualize {
89+
Layout.setRoot(newVerticalLayout(newCommander[]{graphTracer,logTracer}));
90+
graphTracer.set(adjacencyMatrix);
91+
// }
92+
93+
logTracer.println("the possible solutios are");
94+
ham(1);
95+
if(found==0)
96+
logTracer.println("No cycles are found Try with a different graph ");
97+
}
98+
99+
publicstaticvoidmain(String[]args) {
100+
newMain();
101+
}
102+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp