Help with Java Graph Implementation
I have to write up a program that stores verticies into a graph and connect them. The input for the program is given as:
Plot 3 5 to 5 8
Plot 6 1 to 3 5
etc
From this input, I would store a vertix of (3,5)
which are the x
and y
coordinates. I would then have to connect this coordinate to (5,8)
.
My question is, how would I go in implementing this graph? I was thinking I w开发者_JS百科ould need to store the vertixes in an arraylist or a map, and keep the edges in a list too...but since I'm not given an actual max size of the graph, I'm a little bit lost in the overall implementation. Basically, if you guys could give me an idea how to start this, it'd be sweet as.
An easy way to think about graphs is to break them down into their Node and Edge components. (Note: what you call a vertex I call a node. Close enough.)
Let us consider the following options:
// 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;
}
Now a graph is nothing more than:
// option 1
class Graph<V> {
Set<Node<V>> nodes;
}
// option 2
class Graph<V> {
Set<Node<V>> nodes;
Set<Edge<V>> edges;
}
Option 1 is the simplest and easiest to implement. Option 2 gives you some more flexibility, such as adding weights to the edge values.
Now, you have some data at these nodes, correct? For now, let's just have the data be the string representation of the coordinates.
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 = ...
Now as for what functionality you'll want you'd need a more complete list. But this should get you well on your way to understanding how to implement a graph.
You can use a already made library like JDSL for that
精彩评论