我正在尝试创建一个程序,让您从图中附加和删除节点,然后运行 BFS 和 DFS 遍历。
所以我最初add
和connect
节点在运行时......然后我想允许用户点击一个add child to parent
适当地附加一个孩子的按钮。
AddButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e)
{
Nodes nX = new Nodes("X", nodeX, nodeY, nodeWidth, nodeHeight);
appendNode(rootNode, nX);
}
});
}
当我尝试追加一个新节点时,它似乎会覆盖当前的邻接矩阵并将其替换为单个新节点X
作为A
.
我想我知道它为什么这样做......因为我的appendNode()
函数试图通过覆盖旧的并使用新的 nodeList 大小创建一个新的邻接矩阵来更新邻接矩阵:
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
System.out.println(nodeList.size());
size = nodeList.size();
adjMatrix = null;
adjMatrix = new int[size][size];
int fromNode = nodeList.indexOf(parent);
int toNode = nodeList.indexOf(child);
adjMatrix[fromNode][toNode] = 1;
adjMatrix[toNode][fromNode] = 0;
}
public void addNode(Nodes n) {
nodeList.add(n);
}
但我不知道有任何其他方法可以在不覆盖它的情况下实现我想要的。
有什么想法吗?
谢谢!
仅供参考,这是连接节点方法:
public void connectNode(Nodes from, Nodes to)
{
//if matrix is empty..
if(adjMatrix == null)
{
//set matrix [row][col] size to size of nodesList list
size = nodeList.size();
//set dimensions of adj matrix... (6x6 nodesList)
adjMatrix = new int[size][size];
}
int fromNode = nodeList.indexOf(from);
int toNode = nodeList.indexOf(to);
//connect node A to B and B to A, set that i,j position = 1
adjMatrix[fromNode][toNode] = 1;
adjMatrix[toNode][fromNode] = 0;
}
编辑:
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);
adjMatrixCopy[fromNode][toNode] = 1;
adjMatrixCopy[toNode][fromNode] = 0;
//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];
}
}
//still need to add newly added node
//adjMatrix = null;
}