Prompt Title: find a cycle in a directed graph

Created 1 year ago
Votes 0
Views 85 times
IT
0

Prompt Detail:

To detect a cycle in a directed graph, you can use the Depth-First Search (DFS) algorithm. You will need to maintain three states for each vertex: unvisited, in the current DFS branch (temporary marked), and visited (permanent marked). If you find a vertex that is temporarily marked while traversing, it means that there is a cycle in the graph. Here is the C++ code to implement this approach:

cpp
#include <iostream> #include <vector> #include <stack> using namespace std; enum VertexState { UNVISITED, TEMP_MARKED, PERM_MARKED }; bool dfs(int vertex, vector<vector<int>>& graph, vector<VertexState>& state, stack<int>& cycle) { state[vertex] = TEMP_MARKED; cycle.push(vertex); for (int neighbor : graph[vertex]) { if (state[neighbor] == TEMP_MARKED) { return true; } else if (state[neighbor] == UNVISITED && dfs(neighbor, graph, state, cycle)) { return true; } } state[vertex] = PERM_MARKED; cycle.pop(); return false; } vector<int> find_cycle(vector<vector<int>>& graph) { int n = graph.size(); vector<VertexState> state(n, UNVISITED); stack<int> cycle; for (int i = 0; i < n; ++i) { if (state[i] == UNVISITED && dfs(i, graph, state, cycle)) { vector<int> cycle_vec(cycle.size()); for (int j = cycle_vec.size() - 1; j >= 0; --j) { cycle_vec[j] = cycle.top(); cycle.pop(); } return cycle_vec; } } return {}; } int main() { // Example graph represented as an adjacency list vector<vector<int>> graph = { {1, 2}, {3}, {0}, {4}, {5}, {3} }; vector<int> cycle = find_cycle(graph); if (!cycle.empty()) { cout << "Cycle found: "; for (int vertex : cycle) { cout << vertex << " "; } cout << endl; } else { cout << "No cycle found." << endl; } return 0; }

This code defines a simple directed graph using an adjacency list, and then it uses the find_cycle() function to detect if there's any cycle in the graph. If a cycle is found, it prints the vertices in the cycle.

avatar
Dasha
Shared 1 prompt
Created 1 year ago

Leave a Comment

Related Tag Prompts

94
0
151
0
Docker Pro
1 year ago 2023-01-29 06:08:59 AIPRM
308
0
MySQL Marvel
1 year ago 2023-02-13 00:05:32 AIPRM
260
0
Ansible Expert
1 year ago 2023-02-01 09:23:50 AIPRM
193
0
PostgreSQL Pro
1 year ago 2023-02-07 03:45:19 AIPRM
114
0
270
1
Dockerize me
1 year ago 2023-02-17 08:27:58 Chad Thompson-Smith