标签:
学习算法过程中,肯定会遇到图。因为比较熟悉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; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public 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
标签:
原文地址:http://my.oschina.net/amhuman/blog/491477