1

我正在调试使用图形数据的邻接列表表示的广度优先搜索算法:HashMap<String, ArrayList<Edge>>. 每个 String 键是地铁站的名称,每个 ArrayList 是该站的边列表。

我正在使用队列按照遍历的顺序存储图的节点。所以我检查队列中的下一个是孩子的名字。然后我通过使用类似childEdges = stationsAdjacencyList.get(childNodeName);.

我的语法有点不同,但请检查下面的代码。

目前 .get() 函数没有返回 ArrayList 而是null每次都返回。我知道 HashMap 查找正在接收正确的密钥。它只是拒绝从它的相关存储桶中给我任何价值。

    while (!q.empty()) {    // 

        String endpointName; // the Key part for the next node lookup 

        // get next node (single entry of adjacency list)
        Map<String, ArrayList<Edge>> currentNode = (Map<String, ArrayList<Edge>>) q.deque(); 

        HashMap<String, ArrayList<Edge>> nextNode = new HashMap<String, ArrayList<Edge>>();

        for (Map.Entry<String, ArrayList<Edge>> node : currentNode.entrySet()) { // there is only one node

            ++levelCount; // next node iteration is one level down the tree

            for (Edge edge : node.getValue()) {  // for each of this nodes Edges

                endpointName = edge.getEndpoint(); // retrieve the name of adjacent

                if (!endpointName.equals(destination)) { // if it's not the destination



                    levelTracker.put(edge.getParent(), levelCount); // record the level in the tree of this node

                    ArrayList<Edge> nextNodeEdges = adjacencyList.get(endpointName);

                    nextNode.put(endpointName, nextNodeEdges); // create child node from endpoint

                    q.enqueue(nextNode); // add child to queue

                }
                else if (endpointName.equals(destination)) { // if we're done

                    path.add(endpointName); // record the destination in the path (reverse order)

                    getPathBack(edge, levelCount + 1); // + 1 levelCount to indicate destination level in tree 

                    break;
                }
            }
        }

    }

如果代码不是很干净或没有像样的注释,请道歉,它会不断变化。希望有人能告诉我为什么ArrayList<Edge> nextNodeEdges = adjacencyList.get(endpointName);没有获取任何东西。

谢谢!!

4

1 回答 1

2

所以一个很好的测试是看看adjacencyList.get("valid endpoint");在同一个地方用硬编码值调用是否会返回一个非空列表。如果不是adjacencyList,那么它会在某个地方被破坏,如果是,那么它就不像endpointName你想象的那么正确。

于 2011-01-11T04:45:15.103 回答