1

これを解釈する方法は次のとおりです。

nodeName
nodeNameのx座標、nodeNameのy座標
隣接ノードのx座標、その隣接ノードのy座標

...そして残りは隣接するノードの単なる座標です。パスが合法かどうかを確認できるように、これをグラフとして保存する方法を理解しようとしています。たとえば、nodeA-nodeB-nodeCは有効ですが、nodeA-nodeC-nodeDは有効ではありません。

それで、私の最後の質問は、Graphクラスをコーディングし、このデータを読み込んでデータを取り込むための最良の方法は何ですか?

4

3 に答える 3

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);
    }
}
于 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 に答える