我需要从包含多个以邻接表表示的“迷宫”的文本文件制作图形。列表如下:

A,G
A,B,F
B,A,C,G
C,B,D,G
D,C,E
E,D,F,G
F,A,E
G,B,C,E

D,F
A,B,G
B,A,C,E,G
C,B,D,E,G
D,C
E,B,C,G
F,G
G,A,B,C,E,F

F,A
A,B,G
B,A,G
C,D,G
D,C,G
E,F,G
F,E,G
G,A,B,C,D,E,F


每个“迷宫”的第一行包含迷宫的开始节点(第一个字母)和迷宫的结束节点(第二个字母)。

我已经将文本文件解析为所有行的ArrayList(包括空行),然后解析为行的ArrayLists的ArrayList(单独的迷宫列表)。我通过在空白行上拆分完整文本来做到这一点。我的问题是,现在我无法弄清楚如何使用节点类从这些“迷宫”构建图形。这是我的节点类:

package algo2;

import java.util.ArrayList;


public class Node<T>{

    private T value; //this Node<T>'s value
    public ArrayList<Node<T>> connections;
    public boolean isStart;
    public boolean isEnd;
    public boolean visited;

    public Node(T value){
        this.value = value;
        connections = new ArrayList<Node<T>>();
    }

    //returns the value of this Node<T>
    public T getValue(){
        return value;
    }

    //returns true if the node is connected to any other nodes
    public boolean isConnected(){
        if(connections == null){
            return false;
        }
        return true;
    }

    //returns a list of nodes connected to this node
    public ArrayList<Node<T>> getConnections(){
        return connections;
    }

    //sets the node's value
    public void setValue(T value){
        this.value = value;
    }

    //adds a connection from this node to the passed node
    public void connect(Node<T> node){
        connections.add(node);
    }

    public String toString(){
        return value+"";
    }
}


有人可以指出我正确的方向吗?

最佳答案

让我们集中精力设置1个迷宫,然后我们可以对所有迷宫重复该过程。
我尝试编写一种Java语法友好的算法。

因此,据我所知,这是我们第一个迷宫的ArrayList变量...

List<String> preNodes, which contains:
{"A,G", "A,B,F", "B,A,C,G", "C,B,D,G", "D,C,E", "E,D,F,G", "F,A,E", "G,B,C,E"};


因为第一个String具有特殊含义,所以让我们将其与其他字符串分开。 (即,将其设置为单独的String变量,并将其从ArrayList中删除)。

String startAndEnd, which contains: "A,G";
List<String> preNodes, which contains:
{"A,B,F", "B,A,C,G", "C,B,D,G", "D,C,E", "E,D,F,G", "F,A,E", "G,B,C,E"};


现在,让我们首先构建所需的所有节点,然后将它们链接起来。

//Define container for nodes
HashMap<String, Node> nodes = new HashMap<String, Node>();
//Create a node for each letter
for(String s : preNodes) {
    String nodeName = s.charAt(0) + "";
    nodes.put(nodeName, new Node());
}
//Link them up appropriately
for(String s : preNodes) {
    String[] splitS = s.split(","); //1 letter in each array cell.
    Node current = nodes.get(splitS[0]); //Get the node we're going to link up.
    for(int i=1; i<splitS.length; i++) {
        current.connect(nodes.get(splitS[i]));
    }
}
//Finally, set the start and end Node.
String[] splitStartAndEnd = startAndEnd.split(",");
nodes.get(splitStartAndEnd[0]).isStart = true;
nodes.get(splitStartAndEnd[1]).isEnd = true;


我认为应该这样做。现在,“节点”包含整个迷宫,所有迷宫都链接在一起。我在您的代码中发现了一个错误:不过,如果connections.isEmpty()函数的isConnected()函数应返回false,否则为null。它永远不能为null,因为您可以在构造函数中使用新列表对其进行初始化。

关于java - 从文本文件创建迷宫图:Java,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6209966/

10-09 05:34
查看更多