All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.zusmart.basic.graph.DirectedGraphUtil Maven / Gradle / Ivy

Go to download

基础模块,提供配置,日志,SPI,图排序,路径匹配,资源扫描,包扫描,常用工具类

There is a newer version: 0.0.3
Show newest version
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();
	}

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy