Skip to content

Instantly share code, notes, and snippets.

@jarek-przygodzki
Last active December 16, 2015 02:59
Show Gist options
  • Save jarek-przygodzki/5366300 to your computer and use it in GitHub Desktop.
Save jarek-przygodzki/5366300 to your computer and use it in GitHub Desktop.
Detecting cycles in a directed graph
//#!/usr/bin/env groovy
/**
* Finding cycles in a directed graph
*/
class CycleFinder {
// Zbiór wierzchołków w grafie
def V
// Adj(v) - zbiór wierzchołków sąsiadujących z v
def Adj
def visited = [:]
def cycles = []
CycleFinder(V, Adj) {
this.V = V
this.Adj = Adj
}
public findCycles() {
dfs()
return cycles
}
def dfs() {
def path = new Stack()
for(u in V) {
if(!visited[u]) {
dfsVisit(u, path)
}
}
}
def dfsVisit(u, path) {
visited[u] = true
path.push(u)
for(v in Adj(u)) {
int i = path.indexOf(v)
if(i != -1) {
def cycle = new ArrayList(path[i..-1])
cycles.add(cycle)
}
if(!visited[v]) {
dfsVisit(v, path)
}
}
path.pop()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment