Skip to content

Instantly share code, notes, and snippets.

@exhesham
Last active June 8, 2020 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save exhesham/7069c16ec8cf419ae518105a7ef64e8b to your computer and use it in GitHub Desktop.
Save exhesham/7069c16ec8cf419ae518105a7ef64e8b to your computer and use it in GitHub Desktop.
public boolean isCycleUtil(int vertex, boolean[] visited, boolean[] recursiveArr) {
visited[vertex] = true;
recursiveArr[vertex] = true;
//recursive call to all the adjacent vertices
for (int i = 0; i < adjList[vertex].size(); i++) {
//if not already visited
int adjVertex = adjList[vertex].get(i);
if (!visited[adjVertex] && isCycleUtil(adjVertex, visited, recursiveArr)) {
return true;
} else if (recursiveArr[adjVertex])
return true;
}
//if reached here means cycle has not found in DFS from this vertex
//reset
recursiveArr[vertex] = false;
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment