反复使用DFS克隆图形时发生NullPointerException

时间:2019-01-23 04:07:41

标签: java algorithm depth-first-search graph-traversal

我正在尝试在DFS Java中使用iteratively来克隆图形,但是在编译时一直显示NullPointerException。我知道使用recursion的代码要简单得多,但是想以iterative的方式进行尝试。 代码如下所示:

 /**
 * Definition for undirected graph.
 * class UndirectedGraphNode {
 *     int label;
 *     List<UndirectedGraphNode> neighbors;
 *     UndirectedGraphNode(int x) { label = x; neighbors = new ArrayList<UndirectedGraphNode>(); }
 * };
 */

public UndirectedGraphNode cloneGraph(UndirectedGraphNode node) {
    if(node==null) return null;
    Map<UndirectedGraphNode, UndirectedGraphNode> hm = new HashMap<>();
    Stack<UndirectedGraphNode> st = new Stack<>();
    st.push(node);

    while(!st.isEmpty())
    {
        UndirectedGraphNode n = st.pop(); 
        UndirectedGraphNode copy = null;
        if(!hm.containsKey(n)) //if n is cloned before, no need to clone it again
        {
            copy = new UndirectedGraphNode(n.label); //clone parent
            hm.put(n, copy);
        }
        else
            copy = hm.get(n); 

        for(UndirectedGraphNode neighbor: n.neighbors)
        {
            if(!hm.containsKey(neighbor))
            {
                UndirectedGraphNode copy_neighbor = new UndirectedGraphNode(neighbor.label);
                copy.neighbors.add(copy_neighbor); //clone child.
                hm.put(neighbor, copy_neighbor);
                st.push(neighbor);
            }else
                copy.neighbors.add(hm.get(neighbor));//this handles parent node as well.
        }

    }
    return hm.get(node);   
}

在这里,我想做的是从图中获取一个节点并遍历到它的下一个连接节点,或者在这种情况下为neighbor

NullPointerException显示在这一行:

copy.neighbors.add(copy_neighbor);

StackTrace

java.lang.NullPointerException
at line 55, Solution.cloneGraph
at line 102, __Driver__.main

1 个答案:

答案 0 :(得分:0)

您可能没有在async componentDidMount(){ var that = this; var name = '' this.watchId = navigator.geolocation.watchPosition((position)=>{ _retrieveData = async () => { try { await AsyncStorage.getItem('name').then((value)=>name=JSON.parse(value)); } catch (error) { // Error retrieving data } } } 类上初始化neighbors属性。确保在属性声明中进行初始化:

UndirectedGraphNode

或在构造函数中:

private List<UndirectedGraphNode> neighbors = new ArrayList<>();