-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathham_cycle.java
More file actions
69 lines (60 loc) · 1.29 KB
/
ham_cycle.java
File metadata and controls
69 lines (60 loc) · 1.29 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
64
65
66
67
68
69
import java.util.Scanner;
public class ham_cycle
{
static int n;
static int adj[][] = new int[10][10];
static int x[] = new int[10];
static int flag = 0;
public static void main(String args[])
{
Scanner scan = new Scanner(System.in);
System.out.println("Enter the number of vertices");
n = scan.nextInt();
System.out.println("Enter the adjacency matrix");
for(int i = 1; i <= n; i++)
for(int j = 1; j <= n; j++)
adj[i][j] = scan.nextInt();
x[1] = 1;
Hamiltonian(2);
if(flag == 0)
System.out.println("No Hamiltonian cycle present for the given graph");
}
static void Hamiltonian(int k)
{
do
{
NextValue(k);
if(x[k] == 0)
return;
if(k == n)
{
flag = 1;
System.out.println("The Hamiltonian cycle is:");
for(int i = 1; i <= n; i++)
System.out.print(x[i]+" ");
System.out.print("1\n");
}
else
Hamiltonian(k + 1);
}while(true);
}
static void NextValue(int k)
{
int j;
do
{
x[k] = (x[k] + 1) % (n + 1);
if(x[k] == 0)
return;
if(adj[x[k - 1]][x[k]] == 1)
{
for(j = 1; j <= k - 1; j++)
if(x[j] == x[k])
break;
if(j == k)
if((k < n) || ((k == n) && adj[x[n]][x[1]] == 1))
return;
}
}while(true);
}
}