java使用JPanel为BFS遍历设置动画
我正在尝试使用JPanel为BFS遍历设置动画
控制台输出显示算法正在运行
BFS:
A B C D E F
对于给定的图表:
BFS片段:
public void bfs() {
Queue q = new LinkedList();
q.add(rootNode);
rootNode.visited(true);
rootNode.setColor(Color.cyan);
printNode(rootNode);
while (!q.isEmpty()) {
Nodes n = (Nodes)q.remove();
Nodes child = null;
//put all unvisited children in the queue
while ((child = getUnvisitedChildNode(n)) != null)
{
//
child.visited(true);
//visited color = cyan
child.setColor(Color.cyan);
printNode(child);
q.add(child);
}
}
}
所以,我认为在JPanel上制作动画的最好方法是添加一个计时器,它每1秒调用bfs()
。。。并将while
循环更改为if
语句。。。因此,当它被调用时,它将在每个节点上迭代一次,并将其标记为已访问
public void bfs() {
Queue q = new LinkedList();
q.add(rootNode);
rootNode.visited(true);
rootNode.setColor(Color.cyan);
printNode(rootNode);
if (!q.isEmpty()) {
Nodes n = (Nodes)q.remove();
Nodes child = null;
//put all unvisited children in the queue
if ((child = getUnvisitedChildNode(n)) != null)
{
//
child.visited(true);
//visited color = cyan
child.setColor(Color.cyan);
printNode(child);
q.add(child);
}
}
if (q.isEmpty()) {
cancelTimer = true;
}
}
它正在通过节点A
,B
,C
,D
,但现在不会访问B
和F
的子节点
我正在使用一个带有repaint()
的paintComponent在访问时更改节点的颜色
public void paintComponent(Graphics g) {
g.setColor(Color.BLACK);
g.fillRect(0, 0, width, height);
g.setColor(rootNode.getColor());
g.fillRect(rootNode.getX(), rootNode.getY(), rootNode.getWidth(), rootNode.getHeight());
g.setColor(Color.WHITE);
g.drawString(rootNode.getValue(), rootNode.getX()+9, rootNode.getY()+16);
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();
int x = parentNode.getX()-50;
for (Nodes child : nodePrintList) {
g.setColor(child.getColor());
child.setX(x);
child.setY(parentNode.getY()+50);
g.fillRect(child.getX(), child.getY(), child.getWidth(), child.getHeight());
g.setColor(Color.WHITE);
g.drawString(child.getValue(), child.getX()+9, child.getY()+16);
x+=50;
//System.out.print("PARENT: " + parentNode.getValue() + " | x,y: " + parentNode.getX() + ", " + parentNode.getY() + "...\n CHILD: " + child.getValue() + " | x,y: " + child.getX() + ", " + child.getY());
paintComponent(g, child);
g.drawLine(parentNode.getX()+10, parentNode.getY()+23, child.getX()+10, child.getY());
}
}repaint();
}
知道吗
# 1 楼答案
你需要修改你的算法。每次调用
bfs()
,都是在根节点“A”处开始搜索该算法迭代地将“B”、“C”和“D”标记为“A”的子对象,然后。。。就是这样。”A'没有未探视的孩子,所以
bfs()
不再做任何事情;没有while
循环可以用来探索“B”的子元素您需要设置某种形式的持久状态,这样bfs()方法实际上会逐个遍历所有节点Iterative Deepening可能是一个很好的起点,因为DFS可以通过一个简单的堆栈进行迭代