简体   繁体   English

树遍历-运行后将节点追加到邻接矩阵

[英]Tree Traversal - Append node to adjacency matrix after runtime

I'm building a Tree traversal program which allows users to run BFS and DFS traversals, as well as add and remove nodes. 我正在构建一个Tree遍历程序,该程序允许用户运行BFS和DFS遍历以及添加和删除节点。

What I'm stuck on is adding nodes due to problems expanding the adjacency matrix. 由于扩展邻接矩阵存在问题,我坚持要添加节点。 For this example, I'd like to add a new child node X to parent H : 对于此示例,我想向父H添加一个新的子节点X

在此处输入图片说明

For now, I've hard coded the node X , but will allow for custom input later. 现在,我已经对节点X硬编码,但是稍后将允许自定义输入。

User clicks Add Node button: 用户单击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);
        }
   });

Which calls appendNode(): This function is supposed to be creating a new adjacency matrix with the updated size (given the additional node X )... copying the data from the old matrix adjMatrix , then adding an additional slot for th new node X . 调用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;
}

When I click appendNode , it throws this error: 当我单击appendNode ,它将引发此错误:

Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 12
    at Graph.appendNode(Graph.java:306)
    at Graph$3.actionPerformed(Graph.java:141)
 adjMatrixCopy[newSize][col] = 1;

This is wrong. 错了 Maybe you want 也许你想要

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

instead? 代替?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM