我正在构建一个树遍历程序,它允许用户运行 BFS 和 DFS 遍历,以及添加和删除节点。
由于扩展邻接矩阵的问题,我坚持的是添加节点。对于这个例子,我想X
向 parent添加一个新的子节点H
:
目前,我已经对 node 进行了硬编码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)