一个简单的方法来思考的图表是打破他们到他们的节点和边缘部分。 (注:你所谓的顶点我称之为一个节点足够关闭。)
让我们考虑以下选项:
// Option 1
class Node<V> {
V data;
Set<Node<V>> edges;
// if it were a directed graph, you'd need:
// Set<Node<V>> edgesAway;
}
// Option 2
class Node<V> {
V data;
Set<Edge<V>> edges;
// if it were a directed graph, you'd need:
// Set<Edge<V>> edgesAway;
}
class Edge<V> {
Node<V> source;
Node<V> destination;
}
现在的图形无非是:
// option 1
class Graph<V> {
Set<Node<V>> nodes;
}
// option 2
class Graph<V> {
Set<Node<V>> nodes;
Set<Edge<V>> edges;
}
选项1是最简单和最容易实现的。选项2为您提供了更多的灵活性,例如为边缘值添加权重。
现在,您在这些节点上有一些数据,对不对?现在,让我们把数据作为坐标的字符串表示。
class SomeObject {
String data;
int x;
int y;
public boolean equals(Object o) {
if(o instanceof SomeObject) {
SomeObject so = (SomeObject)o;
return so.x == x && so.y == y;
}
return false;
}
public int hashCode() {
return x * 100 + y; // it works... close enough :)
}
}
// somewhere later:
Graph<SomeObject> graph = ...
现在至于你想要什么功能,你需要一个更完整的列表。但是这应该让你理解如何实现一个图表。
如果这是家庭作业,你应该添加[标签:功课]标签 – corsiKa
@glowcoder,是NP – wnnnnn