Last active
December 16, 2015 02:59
-
-
Save jarek-przygodzki/5366300 to your computer and use it in GitHub Desktop.
Detecting cycles in a directed graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//#!/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