Untitled

mail@pastecode.io avatar
unknown
c_cpp
a year ago
1.0 kB
0
Indexable
Never

// Entry Function
string cycleDetection (vector<vector<int>>& edges, int n, int m)
{
    bool visited[n+1] = {false};
    vector<int> adjList[n+1];

    for (auto edge : edges) { // Build adjacency list from given edges info
        adjList[edge[0]].push_back(edge[1]);
        adjList[edge[1]].push_back(edge[0]);
    }

    for (int i = 1; i <= n; i++)
        if (!visited[i]) // Consider all disconnected components of a graph.
            if (cycleDetectUtil(-1, i, visited, adjList))
                return "Yes";

    return "No";
}

bool cycleDetectUtil(int parent, int curr, bool visited[], vector<int> adjList[]) {
    if (visited[curr]) return true; // Found a cycle

    visited[curr] = true;

    for (auto connectedNode : adjList[curr])
        if (connectedNode != parent // don't go to parent, else u will wrongly think that graph has cycle
            && cycleDetectUtil(curr, connectedNode, visited, adjList))
            return true;

    return false; // If no cycle found through all connected nodes of curr
}