你可以这样解释:
节点名称nodeName 的 x coord,nodeName 的 y coord相邻节点的 X 坐标,该相邻节点的 Y 坐标
。其余的只是相邻节点的更多坐标。我正在尝试弄清楚如何将其存储为图表,以便我可以检查路径是否合法。例如,也许nodeA-nodeB-nodeC是合法的,但nodeA-nodeC-nodeD不是。
因此,我的最后一个问题是:编写 Graph 类并通过读取此数据来填充它的最佳方法是什么?
您可以将文件拆分为行组。每个组描述节点。然后解析所有组。
Map<Node, List<Node>> neighbors;
Map<String, Node> nodeByCoords;
// Get node by it's coordinates. Create new node, if it doesn't exist.
Node getNode(String coords) {
String[] crds = coords.split(" ");
int x = Integer.parseInt(crds[0]);
int y = Integer.parseInt(crds[1]);
String key = x + " " + y;
if (!nodeByCoords.containsKey(key)) {
Node node = new Node();
node.setX(x);
node.setY(y);
nodeByCoords.put(key, node);
neighbords.put(node, new ArrayList<Node>());
}
return nodeByCoords.get(key);
}
// Create node (if not exists) and add neighbors.
void List<String> readNode(List<String> description) {
Node node = getNode(description.get(1));
node.setName(description.get(0));
for (int i = 2; i < description.size(); i++) {
Node neighbor = getNode(description.get(i));
neighbors.get(node).add(neighbor);
}
}
// Splits lines to groups. Each group describes particular node.
List<List<String>> splitLinesByGroups (String filename) {
BufferedReader reader = new BufferedReader(new FileReader(filename));
List<List<String>> groups = new ArrayList<List<String>>();
List<String> group = new ArrayList<String>();
while (reader.ready()) {
String line = reader.readLine();
if (Character.isLetter(line.charAt())) {
groups.add(group);
group = new ArrayList<String>();
}
group.add(line);
}
groups.add(group);
return groups;
}
// Read file, split it to groups and read nodes from groups.
void readGraph(String filename) {
List<List<String>> groups = splitLineByGroups(filename);
for (List<String> group: groups) {
readNode(group);
}
}
我认为没有必要以某种方式存储节点来找出路径是否合法:您可以在读取它们时检查下一个节点的合法性。下一个节点是合法的,当且仅当它的坐标与前一个节点相差不超过 1 时。
您可能需要考虑使用 JGraphT
您可以只创建SimpleGraph
的实例,并用节点和边填充它:
// Define your node, override 'equals' and 'hashCode'
public class Node {
public int x, y;
Node (int _x, int _y) {
x = _x;
y = _y;
}
@Override public boolean equals (Object other) {
if ( (other.x == x)
&& (other.y == y))
return true;
return false;
}
/* Override hashCode also */
}
// Later on, you just add edges and vertices to your graph
SimpleGraph<Node,Edge> sg;
sg.addEdge (...);
sg.addVertex (...);
最后,您可以使用DijkstraShortestPath
来查找路径是否存在: