com.zusmart.base.graph.DirectedGraphUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zusmart-base Show documentation
Show all versions of zusmart-base Show documentation
提供基础的工具类及方法类,Logging,Scanner,Buffer,NetWork,Future,Thread
package com.zusmart.base.graph;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class DirectedGraphUtil {
private static final String MARKED = "MARKED";
private static final String COMPLETE = "COMPLETE";
private DirectedGraph graph;
private Map marks;
private List verticesInCycles;
public DirectedGraphUtil(DirectedGraph graph) {
this.graph = graph;
this.marks = new HashMap();
this.verticesInCycles = new ArrayList();
}
public List getVerticesInCycles() {
return this.verticesInCycles;
}
public boolean hasCycle() {
this.marks.clear();
this.verticesInCycles.clear();
for (T v : this.graph) {
if (!marks.containsKey(v)) {
mark(v);
}
}
return !this.verticesInCycles.isEmpty();
}
public Set getSort() {
Set result = new LinkedHashSet();
Iterator iter = this.graph.iterator();
while (iter.hasNext()) {
T current = iter.next();
int count = this.graph.getEdges(current).size();
if (count == 0) {
result.add(current);
}
}
iter = this.graph.iterator();
while (iter.hasNext()) {
T current = iter.next();
int count = this.graph.getEdges(current).size();
if (count == 0) {
continue;
}
result.addAll(this.search(current));
result.add(current);
}
return result;
}
private Set search(T head) {
Set result = new LinkedHashSet();
Set edges = this.graph.getEdges(head);
if (null == edges || edges.size() == 0) {
return result;
}
Iterator iter = edges.iterator();
while (iter.hasNext()) {
T current = iter.next();
int count = this.graph.getEdges(current).size();
if (count == 0) {
result.add(current);
} else {
result.addAll(this.search(current));
result.add(current);
}
}
return result;
}
private boolean mark(T vertex) {
List localCycles = new ArrayList();
marks.put(vertex, MARKED);
for (T u : this.graph.getEdges(vertex)) {
if (marks.containsKey(u) && marks.get(u).equals(MARKED)) {
localCycles.add(vertex);
} else if (!marks.containsKey(u)) {
if (mark(u)) {
localCycles.add(vertex);
}
}
}
marks.put(vertex, COMPLETE);
verticesInCycles.addAll(localCycles);
return !localCycles.isEmpty();
}
}