forked from nitind2411/hacktoberfest-2022-DSA-CP
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHamiltonian Path.cpp
72 lines (56 loc) · 1.34 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
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
#include<bits/stdc++.h>
using namespace std;
class Solution
{
private:
bool dfs(int parent,vector<bool> &vis,unordered_map<int,vector<int>> &mp,int cnt){
if(cnt == mp.size()){
return true;
}
vis[parent] = true;
for(auto &it : mp[parent]){
if(vis[it] == false){
if(dfs(it,vis,mp,cnt+1))
return true;
}
}
vis[parent] = false;
return false;
}
public:
bool check(int N,int M,vector<vector<int>> Edges)
{
unordered_map<int,vector<int>> mp;
for(int i=0;i<Edges.size();i++){
int u = Edges[i][0];
int v = Edges[i][1];
mp[u].push_back(v);
mp[v].push_back(u);
}
vector<bool> vis(mp.size(),false);
for(int i=0;i<mp.size();i++){
int cnt = 1;
if(dfs(i+1,vis,mp,cnt))
return true;
}
return false;
}
};
int main()
{
int N,M,X,Y;
cin>>N>>M;
vector<vector<int>> Edges;
for(int i=0;i<M;i++)
{
cin>>X>>Y;
Edges.push_back({X,Y});
}
Solution obj;
if(obj.check(N,M,Edges)){
cout<<"1"<<endl;
}
else
cout<<"0"<<endl;
}
// } Driver Code Ends