gpt4 book ai didi

java - 给定相邻节点的坐标构建图

转载 作者:太空宇宙 更新时间:2023-11-04 08:18:10 25 4
gpt4 key购买 nike

你可以这样解释:

nodeNamenodeName's x-coord, nodeName's y-coordx-coord of an adjacent node, y-coord of that adjacent node

...剩下的只是相邻节点的更多坐标。我正在尝试弄清楚如何将其存储为图表,以便我可以检查路径是否合法。例如,也许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);
}
}

关于java - 给定相邻节点的坐标构建图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10064248/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com