-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy pathhamiltonian_paths.cpp
More file actions
70 lines (57 loc) · 1.2 KB
/
hamiltonian_paths.cpp
File metadata and controls
70 lines (57 loc) · 1.2 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
#include <bits/stdc++.h>
using namespace std;
struct Edge
{
int src;
int dest;
};
class Graph
{
public:
vector<vector<int>> adjList;
Graph(vector<Edge> &edges, int N)
{
adjList.resize(N);
for (auto e : edges)
{
adjList[e.src].push_back(e.dest);
adjList[e.dest].push_back(e.src);
}
}
};
void hamilton(Graph &G,int start,int v,vector<int> &path,vector<bool> &visited){
if(path.size() == v){
for(auto e : path)
cout << e << " ";
cout << endl;
}
for(auto dest : G.adjList[start]){
if(!visited[dest]){
visited[dest] = true;
path.push_back(dest);
hamilton(G,dest,v,path,visited);
visited[dest] = false;
path.pop_back();
}
}
}
int main()
{
vector<Edge> edges;
int v, e;
cin >> v >> e;
for (int i = 0; i < e; i++)
{
int src, dest;
cin >> src >> dest;
Edge e;
e.src = src;
e.dest = dest;
edges.push_back(e);
}
Graph g(edges, v);
int start = 0;
vector<int> path = {};
vector<bool> visited(v);
hamilton(g,start,v,path,visited);
}