forked from sourav-122/hacktoberfest2022
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Hamiltonian Path.cpp
39 lines (39 loc) · 1 KB
/
Hamiltonian Path.cpp
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
class Solution
{
private :
bool isHamiltonianPathExists(vector<int> graph[],vector<int> &visited,int cnt,int node,int n)
{
visited[node] = 1;
for(auto &adjNode : graph[node])
{
if(!visited[adjNode])
{
if(isHamiltonianPathExists(graph,visited,cnt+1,adjNode,n))
return true;
}
}
if(cnt == n) return true;
visited[node] = 0;
return false;
}
public:
bool check(int N,int M,vector<vector<int>> Edges)
{
vector<int> graph[N+1];
for(int i=0; i<M; i++)
{
graph[Edges[i][0]].push_back(Edges[i][1]);
graph[Edges[i][1]].push_back(Edges[i][0]);
}
vector<int> visited(N+1,0);
for(int i=1; i<=N; i++)
{
if(visited[i] == 0)
{
if(isHamiltonianPathExists(graph,visited,1,i,N))
return true;
}
}
return false;
}
};