我刚刚实现了 BFS 和 DFS 算法。
我的最终目标是将算法动画到 JPanel 上......
但首先我想以各自的父子关系将节点绘制到屏幕上:
虽然是这样出来的...
我想要做的是设置一个孩子的(x,y)
=父母的(x, y)
+ 50px ...像这样:
g.fillRect(x+=50, y=parentNode.getY()+50, child.getWidth(), child.getHeight());
这样,父母的孩子将永远低于父母并从父母那里偏移......
参考图片...
节点B's
(x,y)将等于父节点A's
(x + 50,y + 50)......类似的东西......我知道最终我会想要x
左边的偏移量,所以它会在下面得到一个很好的金字塔效果家长...
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(Color.CYAN);
g.fillRect(rootNode.getX(), rootNode.getY(), rootNode.getWidth(), rootNode.getHeight());
paintComponent(g, rootNode);
}
public void paintComponent(Graphics g, Nodes parentNode) {
//keep generating new nodePrintList to load with new Children
ArrayList<Nodes> nodePrintList = new ArrayList<Nodes>();
//base case: end of nodeList
if (nodeList.indexOf(parentNode)==nodeList.size()-1) {
System.out.println("\nend");
}
else {
//traverse nodeList recursively
nodePrintList = getChildren(parentNode);
//loop through and print all children of node n
System.out.println();
for (Nodes child : nodePrintList) {
System.out.print("PARENT: " + parentNode.getValue() + " | x,y: " + parentNode.getX() + ", " + parentNode.getY() + "...\n CHILD: " + child.getValue() + " | x,y: " + child.getX() + ", " + child.getY());
g.setColor(Color.GREEN);
g.fillRect(x+=50, y=parentNode.getY()+50, child.getWidth(), child.getHeight());
paintComponent(g, child);
}
}
}
知道如何实现吗?为什么孩子们都出现在 A 下的同一层?节点E
并且F
应该在节点之下B
我知道递归正在工作,因为控制台输出System.out.print("Parent: " + parentNode.getValue() + ". Child: " + child.getValue());
是:
PARENT: A | x,y: 180, 100...
CHILD: B | x,y: 180, 100
PARENT: B | x,y: 205, 150...
CHILD: E | x,y: 180, 100
PARENT: B | x,y: 205, 150...
CHILD: F | x,y: 180, 100
PARENT: A | x,y: 180, 100...
CHILD: C | x,y: 180, 100
PARENT: A | x,y: 180, 100...
CHILD: D | x,y: 180, 100
PARENT: D | x,y: 205, 150...
CHILD: G | x,y: 180, 100
end