树遍历 - 在运行时之后将节点附加到邻接矩阵

时间:2013-06-21 17:21:43

标签: java algorithm swing breadth-first-search

我正在构建一个Tree遍历程序,它允许用户运行BFS和DFS遍历,以及添加和删除节点。

由于扩展邻接矩阵的问题,我所坚持的是添加节点。对于此示例,我想将新的子节点X添加到父H

enter image description here

目前,我已经对节点X进行了硬编码,但稍后会允许自定义输入。

用户点击Add Node按钮:

    //try and create and connect node via button
AddButton.addActionListener(new ActionListener() {   
        public void actionPerformed(ActionEvent e)
        {   
            Nodes nX = new Nodes("X", nodeX, nodeY, nodeWidth, nodeHeight);
            appendNode(rootNode, nX);
        }
   });

调用appendNode():该函数应该创建一个具有更新大小的新邻接矩阵(给定附加节点X)...复制旧矩阵adjMatrix中的数据,然后为新节点X添加一个额外的插槽。

public void appendNode(Nodes parent, Nodes child) {
    //add new node X to nodeList
    addNode(child);

    //loop through all nodes again to be connected, plus new one... then create new adjMatrix
    int newSize = nodeList.size();

    //make a new adj matrix of the new size...
    int[][] adjMatrixCopy = new int[newSize][newSize];

    int fromNode = nodeList.indexOf(parent);
    int toNode = nodeList.indexOf(child);

    //copy adjMatrix data to new matrix...
    for (int i = 0; i < adjMatrix.length; i++) {    
        for (int j = 0; j < adjMatrix[i].length; j++) {
            adjMatrixCopy[i][j] = adjMatrix[i][j];
        }
    }
    for (int col = 0; col < newSize; col++) {
        adjMatrixCopy[newSize][col] = 1;
    }
//  still need to add newly added node 

//  adjMatrixCopy[fromNode][toNode] = 1;
//  adjMatrixCopy[toNode][fromNode] = 0;
//  adjMatrix = null;
}

当我点击appendNode时,会抛出此错误:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 12
    at Graph.appendNode(Graph.java:306)
    at Graph$3.actionPerformed(Graph.java:141)

1 个答案:

答案 0 :(得分:1)

 adjMatrixCopy[newSize][col] = 1;

这是错误的。也许你想要

 adjMatrixCopy[newSize - 1][col] = 1;

代替?