-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathGFG Hamiltonian Path
42 lines (39 loc) · 962 Bytes
/
GFG Hamiltonian Path
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
class Solution
{
public:
bool check(int n,int m,vector<vector<int>> edges)
{
vector<vector<int>> adj(n+1);
for(int i=0;i<edges.size();i++)
{
adj[edges[i][0]].push_back(edges[i][1]);
adj[edges[i][1]].push_back(edges[i][0]);
}
vector<int> vis(n+1,0);
vector<int> path;
for(int i=1;i<=n;i++)
{
if(dfs(i,n,adj,vis,path))
return true;
}
return false;
}
bool dfs(int node,int n,vector<vector<int>> &adj,vector<int> &vis,vector<int> &path)
{
path.push_back(node);
vis[node]=1;
if(path.size()==n)
return true;
for(int x:adj[node])
{
if(!vis[x])
{
if(dfs(x,n,adj,vis,path))
return true;
}
}
path.pop_back();
vis[node]=0;
return false;
}
};