Skip to content

Commit 200e94e

Browse files
authored
Merge pull request #123 from ayyush08/round-trip-problem
solution for the Round Trip problem in graph algorithms
2 parents 5c7a056 + f869a20 commit 200e94e

File tree

1 file changed

+81
-0
lines changed

1 file changed

+81
-0
lines changed

4_graph_algorithms/Round-Trip.cpp

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
int n, m;
5+
vector<vector<int>> adj;
6+
vector<bool> visited;
7+
vector<int> parent;
8+
int cycle_start, cycle_end;
9+
10+
bool isCycle(int v, int p)
11+
{
12+
visited[v] = true;
13+
for (int child : adj[v])
14+
{
15+
if (child == p)
16+
continue; // Skip the parent node
17+
if (visited[child])
18+
{
19+
cycle_end = v;
20+
cycle_start = child;
21+
return true;
22+
}
23+
parent[child] = v;
24+
if (isCycle(child, v))
25+
{
26+
return true;
27+
}
28+
}
29+
return false;
30+
}
31+
32+
int main()
33+
{
34+
ios::sync_with_stdio(false);
35+
cin.tie(nullptr);
36+
cin >> n >> m;
37+
adj.resize(n);
38+
for (int i = 0; i < m; i++)
39+
{
40+
int u, v;
41+
cin >> u >> v;
42+
u--;
43+
v--;
44+
adj[u].push_back(v);
45+
adj[v].push_back(u);
46+
}
47+
visited.assign(n, false);
48+
parent.assign(n, -1);
49+
cycle_start = -1;
50+
for (int v = 0; v < n; v++)
51+
{
52+
if (!visited[v] && isCycle(v, parent[v]))
53+
break;
54+
}
55+
56+
if (cycle_start == -1)
57+
{
58+
cout << "IMPOSSIBLE" << '\n';
59+
}
60+
else
61+
{
62+
vector<int> cycle;
63+
cycle.push_back(cycle_start);
64+
for (int v = cycle_end; v != cycle_start; v = parent[v])
65+
{
66+
cycle.push_back(v);
67+
}
68+
cycle.push_back(cycle_start);
69+
cout << cycle.size() << '\n';
70+
for (int v : cycle)
71+
{
72+
cout << v + 1 << ' ';
73+
}
74+
}
75+
return 0;
76+
}
77+
78+
//Time Complexity: O(n + m) where n is number of nodes and m is number of edges
79+
//Space Complexity: O(n + m) for adjacency list and O(n) for visited and parent arrays
80+
81+
//Problem link: https://cses.fi/problemset/task/1669/

0 commit comments

Comments
 (0)