com.zusmart.basic.graph.DirectedGraphUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of zusmart-basic Show documentation
Show all versions of zusmart-basic Show documentation
基础模块,提供配置,日志,SPI,图排序,路径匹配,资源扫描,包扫描,常用工具类
package com.zusmart.basic.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();
}
}