我正在使用图形数据结构制作 Hunt the Wumpus 游戏。其中的每个顶点都是一个大小为 4 的数组,表示每个方向,北南东西。方向存储在枚举中。当一个顶点与另一个顶点连接时,它的邻接关系应该发生变化,以便它与另一个顶点连接(我仍然对此感到困惑——为什么我的顶点是一个大小为 4 的数组但只有一个方向)。
当我将一个顶点与另一个顶点连接并打印出邻居的数组列表时,我得到了一个奇怪的输出。当我打印未连接的顶点时,我得到邻居的 [null, null, null, null];当我打印连接的顶点时,我得到 [null,null,null,[null,null,null,null]。我不知道邻居应该是什么——它们应该打印为代表方向枚举索引的整数还是方向?应该打印什么?
import java.util.ArrayList;
import java.util.Collection;
enum Direction{
EAST,
WEST,
NORTH,
SOUTH
}
public class Vertex extends Agent implements Comparable<Vertex>{
private Vertex[] connections;
private Direction dir;
private int cost;
private boolean marked;
public Vertex(double x0, double y0){
super( x0, y0);
connections = new Vertex[4];
this.dir = dir;
this.cost = cost;
this.marked = marked;
}
public Direction opposite(Direction dir) {
//that returns the compass opposite of a direction (i.e. South for North...)
if(dir == Direction.EAST){
dir = Direction.WEST;
}
else if(dir == Direction.WEST){
dir = Direction.EAST;
}
else if(dir == Direction.NORTH){
dir = Direction.SOUTH;
}
else dir = Direction.NORTH;
return dir;
}
void connect(Vertex other, Direction dir){
//modify the object's adjacency list/map so that it connects with the other Vertex. This is a uni-directional link.
connections[dir.ordinal()] = other;
}
Vertex getNeighbor(Direction dir){
//returns the Vertex in the specified direction or null.
return this.connections[dir.ordinal()];
}
Collection getNeighbors(){
//returns a Collection, which could be an ArrayList, of all of the object's neighbors.
ArrayList<Vertex> neighborList = new ArrayList<Vertex>();
for (Direction dir: Direction.values()){
neighborList.add(this.getNeighbor(dir));
}
return neighborList;
}
public int getCost(){
return this.cost;
}
public int setCost(int c){
return this.cost = c;
}
public boolean getMarked(){
return this.marked;
}
public boolean setMarked(boolean m){
return this.marked = m;
}
public int compareTo(Vertex other){
return (this.cost - other.cost);
}
/*
* returns a string containing the number of neighbors, the cost, and the marked flag
*/
public String toString(){
String s = "";
s += this.getNeighbors() + "\n" ;
s += "cost: " + this.cost + "\n";
s += "marked: " + this.marked;
return s;
}
public static void main (String args[]){
Vertex newE = new Vertex(0.5, 0.5);
Vertex newerE = new Vertex(0.123, 1.56);
newE.connect(newerE, Direction.SOUTH);
newE.setCost(1);
newE.setMarked(true);
System.out.println(newE.toString());
}
}