Professional Documents
Culture Documents
WINSEM2023-24 PSTS601L SS VL2023240500309 2024-04-25 Reference-Material-I
WINSEM2023-24 PSTS601L SS VL2023240500309 2024-04-25 Reference-Material-I
CYCLE
Hamiltonian Cycle
Introduction
Hamiltonian cycle:
IO Format
Input
Adjacency Matrix or Adjacency List representing the graph
If it is an adjacency matrix, it will be a 2D array with ‘1’ at (i,j) if there is a path
from i to j.
Output
Array which represents the Hamiltonian Path
a -> Graph
b -> Adj. List
c- > Adj. Matrix
Hamiltonian Cycle
Example
Hamiltonian Cycle
Backtracking Solution
Program
hamilt1.java
Sample IO
Input Output
8 012376540
01011000
10100100 Explanation:
01010010 First line in input is the number of vertices
10100001 The next lines would be the matrix
10000101
01001010
00100101
00011010
Hamiltonian Cycle
import java.util.Scanner;
import java.util.Arrays; catch (Exception e)
public class EthCode {
{ System.out.println(e.getMessage());
private int V, pathCount; display();
private int[] path; }
private int[][] graph; }
public void findHamiltonianCycle(int[][] g)
{ public void solve(int vertex) throws Exception
V = g.length; {
path = new int[V]; if (graph[vertex][0] == 1 && pathCount == V)
Arrays.fill(path, -1); throw new Exception("Solution found");
graph = g; if (pathCount == V)
try return;
{
path[0] = 0;
pathCount = 1;
solve(0);
System.out.println("No solution");
}
Hamiltonian Cycle
https://learn.codemithra.com