[英]BFS graph traversal - Append new node to adjacency matrix
我正在尝试创建一个程序,让您追加并从图中删除节点,然后运行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;
}
通过消隐邻接矩阵并将其替换为具有更新大小的新矩阵,除(from,to)和(to,from)之外的所有单元将为零。 您需要使用新大小创建一个新的邻接矩阵,从旧的大小复制数据,然后才覆盖旧的。
为什么不是邻接名单? 或使用可以在运行中递增的集合的邻接矩阵?
我认为使用阵列会导致这个长期存在的问题。 如果要使用邻接矩阵,则应使用集合。 那说,如果你只是做一个BFS,邻接列表会更快,所以我建议。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.