我正在構建一個樹遍歷程序,它允許用戶運行BFS和DFS遍歷,以及添加和刪除節點。樹遍歷 - 追加節點到運行後的鄰接矩陣
我堅持的是由於擴展鄰接矩陣的問題而增加節點。對於這個例子,我想一個新的子節點X
添加到父H
:
現在,我已經硬編碼的節點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)
由於無論如何您都需要動態更改數組大小的開銷,您是否考慮過使用ArrayList而不是實際的數組?它具有非常好的測試,用於更改大小的工作代碼。 –