1

您可以这样解释:

节点名
nodeName 的 x 坐标,nodeName 的 y 坐标
相邻节点的 x 坐标,该相邻节点的 y 坐标

...其余的只是相邻节点的更多坐标。我试图弄清楚如何将其存储为图表,以便检查路径是否合法。例如,也许 nodeA-nodeB-nodeC 是合法的,但 nodeA-nodeC-nodeD 不是。

所以,我的最后一个问题是:编写 Graph 类并通过读入这些数据来填充它的最佳方法是什么?

4

3 回答 3

1

You can split file to groups of lines. Each group describes node. And then parse all groups.

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);
    }
}
于 2012-04-08T16:35:28.637 回答
0

我认为没有必要以某种方式存储节点来确定路径是否合法:您可以在读取它们时检查下一个节点的合法性。下一个节点是合法的当且仅当它的坐标与之前的坐标相差不超过 1。

于 2012-04-08T16:22:54.570 回答
0

您可能要考虑使用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来查找路径是否存在:

于 2012-04-08T16:41:35.407 回答