建立给定相邻节点坐标的图形

时间:2012-04-08 16:09:12

标签: java graph

您可以这样解释:

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

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

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

3 个答案:

答案 0 :(得分:1)

您可以将文件拆分为多组。每个组描述节点。然后解析所有组。

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 :(得分:0)

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

答案 2 :(得分: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查找路径是否存在: