【发布时间】:2014-11-08 19:30:34
【问题描述】:
我在框架中使用回溯来解决边界修剪的图形着色问题。 图的每种可能状态(即可以放在图上的每种颜色组合)都由一个 State 对象表示。该框架要求每个州产生它所有的孩子,选择具有最佳界限的一个,并重复寻找最佳解决方案,并在此过程中进行边界修剪。我遇到的麻烦是:
当我在状态上调用 nextChild() 时,它会将由该状态产生的前一个孩子更改为与刚刚产生的孩子相同。
这是我认为与我的代码相关的部分:
public State nextChild() {
// System.out.println("currentColor: "+ colors.get(currentColor) + " firstUncolored " + this.firstUncolored);
// previous line for debugging
GraphColoringState child = childSetup();
child.gcolors[firstUncolored] = colors.get(currentColor++);
if(this.currentColor == colors.size()){
this.currentColor = 0;
this.hasMoreChildren = false;
}
return child;
}
private GraphColoringState childSetup() {
GraphColoringState theClone = new GraphColoringState(graph, colors);
theClone.gcolors = this.gcolors;
theClone.firstUncolored = this.firstUncolored +1;
theClone.currentColor = 0;
return theClone;
}
当我制作和打印这样的孩子时:
State s = new GraphColoringState(graph, colors);
System.out.println(s);
State s1 = s.nextChild();
System.out.println(s1);
State s2 = s.nextChild();
System.out.println(s2);
State s3 = s.nextChild();
System.out.println(s3);
我得到这个输出:
, , , , , ,
Red, , , , , ,
Green, , , , , ,
Blue, , , , , ,
但是当我以这种方式制作和打印时:
System.out.println(s);
State s1 = s.nextChild();
State s2 = s.nextChild();
State s3 = s.nextChild();
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
我得到了这个不幸的输出:
, , , , , ,
Blue, , , , , ,
Blue, , , , , ,
Blue, , , , , ,
我说这个输出很不幸,因为为了让回溯框架工作,我需要同时存储所有这些具有不同值的子节点。我曾尝试在每个州中使用数组实例变量来存储其子项,但无济于事。
为什么我的代码会改变我已经产生的孩子的值?
请,谢谢! :)
【问题讨论】:
标签: java state backtracking