You are lucky I'm bored. :)
We'll start with the set up; first of all you'll need the player and nodes. You can't have a simple reference to another player as the noe also has an attribute - length.
I have missed a lot of code here, but make sure that the two players on either side of the node always have the node in their collection.
class Player {
private List<node> connections;
List<node> getConnections() {
return this.connections;
}
}
class Node {
private Player from;
private Player to;
private int length;
Player getNext (Player from) {
if (from.equals(this.from)) {
return this.to;
} else if (from.equals(this.to)) {
return this.from;
}
return null;
}
}
Next up is to have a seperate class for calculating the route. I like this approach as it abstracts this detailed point away from the Player class.
The algorithm is reasonably simple:
0. Starting from the first record the distance travelled.
1. For each node from the current node:
2. If it is a new add it to the list, or
3. If the length travelled is shorter then current distance, update the route.
After the noes have all been traversed, the final shortest route is in the current distance instance for the 'to' Player.
class Route {
private List<node> nodes;
private int length;
void buildRoute (Player from, Player to) {
ArrayList<distance> distances = new ArrayList<distance>();
distances.add(new Distance(from));
int pos = 0;
while (pos < distances.size()) {
Distance current = distances.get(pos);
for (Node node : current.getConnections() {
int length = current.length + node.getLength();
Player dest = node.getNext(current);
Distance next = null;
for (Distance d : distances) {
if (d.player.equals(dest)) {
next = d;
break;
}
}
if (next == null) {
next = new Distance(dest);
next.length = length+1;
distances.add(next);
}
if (length < next.length) {
next.nodes = current.nodes.clone();
next.nodes.add(node);
next.length = length;
}
}
pos++;
}
for (Distance d : distances) {
if (d.player.equals(to)) {
this.nodes = d.nodes;
this.length = d.length;
break;
}
}
}
class Distance {
Player player;
ArrayList<nodes> nodes;
int length;
Distance (Player player) {
this.player = player;
this.length = 0;
this.nodes = new ArrayList<nodes>();
}
public boolean equals(Object o) {
return (this.player.equals((Distance)o.player));
}
}
}