-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHamiltonianPath.java
More file actions
134 lines (108 loc) · 3.38 KB
/
HamiltonianPath.java
File metadata and controls
134 lines (108 loc) · 3.38 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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
import java.io.*;
import java.util.*;
public class HamiltonianPath {
public static void main(String[] args) {
FastReader in = new FastReader();
int nodes = in.nextInt();
int edges = in.nextInt();
Graph g = new Graph(nodes);
for (int i = 0 ; i < edges ; i++) {
int u = in.nextInt();
int v = in.nextInt();
g.addEdge(u, v);
}
if (g.Hamiltonian_Paths(arr)) System.out.println("YES");
else System.out.println("NO");
}
static class Graph {
int nodes;
LinkedList<Integer> adj[] ;
Graph(int nodes) {
this.nodes = nodes;
adj = new LinkedList[nodes + 1];
for (int i = 1; i <= nodes; i++) {
adj[i] = new LinkedList<Integer>();
}
}
public void addEdge(int u, int v) {
adj[u].add(v);
adj[v].add(u);
}
public void BFS(int s) {
boolean[] visited = new boolean[nodes + 1];
Queue<Integer> q = new LinkedList<Integer>();
visited[s] = true;
q.add(s);
int element;
while (q.size() != 0) {
element = q.remove();
for (int e : adj[element]) {
if (!visited[e]) {
visited[e] = true;
q.add(e);
}
}
}
}
boolean Hamiltonian_Paths(boolean[][] adj) {
boolean[][] dp = new boolean[this.nodes][1 << this.nodes];
for (int i = 0; i < nodes; i++) {
dp[i][1 << i] = true;
}
for (int i = 0; i < (1 << nodes); i++) {
for (int j = 0; j < nodes; j++) {
if ((i & (1 << j)) > 0) {
for (int k = 0; k < nodes; k++) {
if ((i & (1 << k)) > 0 && adj[k][j] && k != j && dp[k][i ^ (1 << j)]) {
dp[j][i] = true;
break;
}
}
}
}
}
for (int i = 0; i < nodes; i++) {
if (dp[i][(1 << nodes) - 1]) {
return true;
}
}
return false;
}
}
static class FastReader {
BufferedReader br;
StringTokenizer st;
public FastReader() {
br = new BufferedReader(new
InputStreamReader(System.in));
}
String next() {
while (st == null || !st.hasMoreElements()) {
try {
st = new StringTokenizer(br.readLine());
} catch (IOException e) {
e.printStackTrace();
}
}
return st.nextToken();
}
int nextInt() {
return Integer.parseInt(next());
}
long nextLong() {
return Long.parseLong(next());
}
double nextDouble() {
return Double.parseDouble(next());
}
String nextLine() {
String str = "";
try {
str = br.readLine();
} catch (IOException e) {
e.printStackTrace();
}
return str;
}
}
}