標籤:
學習演算法過程中,肯定會遇到圖。因為比較熟悉java,所以習慣用java去實現一遍,但是我一直沒有找到樹和圖的資料結構的jar包,好遺憾。
今天搜拓撲排序的實現,無意中發現了一個圖的Java實現【1】,很棒,方正比我自己的好很多,map的使用是個亮點:
enum Color {WHITE, GRAY, BLACK}static class Vertex {private String name; private Color color; //用來標記處理狀態private Vertex parent; //搜尋結束可以得到多棵樹private int discover; //開始處理時間private int finish; //結束處理時間public Vertex(String name) {this.name = name;this.color = Color.WHITE;}public String getName() {return name;}public void setName(String name) {this.name = name;}public Color getColor() {return color;}public void setColor(Color color) {this.color = color;}public Vertex getParent() {return parent;}public void setParent(Vertex parent) {this.parent = parent;}public int getDiscover() {return discover;}public void setDiscover(int discover) {this.discover = discover;}public int getFinish() {return finish;}public void setFinish(int finish) {this.finish = finish;}@Overridepublic int hashCode() {final int prime = 31;int result = 1;result = prime * result + ((name == null) ? 0 : name.hashCode());return result;}@Overridepublic boolean equals(Object obj) {if (this == obj)return true;if (obj == null)return false;if (getClass() != obj.getClass())return false;Vertex other = (Vertex) obj;if (name == null) {if (other.name != null)return false;} else if (!name.equals(other.name))return false;return true;}}static class Graph {private Set<Vertex> vertexSet = new HashSet<Vertex>();// 相鄰的節點private Map<Vertex, Vertex[]> adjacencys = new HashMap<Vertex, Vertex[]>();public Set<Vertex> getVertexSet() {return vertexSet;}public void setVertexSet(Set<Vertex> vertexSet) {this.vertexSet = vertexSet;}public Map<Vertex, Vertex[]> getAdjacencys() {return adjacencys;}public void setAdjacencys(Map<Vertex, Vertex[]> adjacencys) {this.adjacencys = adjacencys;}}
附上我自己的實現,傻傻的按書上的定義來,簡直low爆了:
public static class ALNode{public ALNode(String name){this.name = name;}String name;ArcNode first;} public static class ArcNode{public ArcNode(ALNode node){this.node = node;}ALNode node;ArcNode next;} public static class ALGraph{ALNode nlist[];}
參考資料
【1】拓撲排序java實現 http://blog.csdn.net/kimylrong/article/details/17220455
圖的鄰接表標記法的JAVA實現