回溯法,是一种枚举法,就是尝试所有结果,最后得到最优解。
从初始状态出发,按照深度优先搜索的方法,根据产生子节点的条件约束,搜索问题的解。当发现当前节点不满足求解条件时,就回溯,尝试其他路径。
例子:地图着色
有一幅地图和m种颜色,怎样涂色才能让相邻区域的是不同的颜色?
下面是抽象化后的结果,用图来表示,弧表示两个顶点相邻,即地图中的两个区域相邻。
class tu{
constructor(){
//this.points = 0;
//this.arcs = 0;
this.point_array = new Array();
this.point_arc = new Array();
this.colors = ['blue','green','red'];
this.paintColor = new Array();
}
create(){
this.point_array = ['A', 'B', 'C', 'D', 'E', 'F', 'G'];
this.point_arc = [[0,1,1,1,0,0,0],
[1,0,1,0,1,0,0],
[1,1,0,1,1,0,0],
[1,0,1,0,1,0,1],
[0,1,1,1,0,1,1],
[0,0,0,0,1,0,1],
[0,0,0,1,1,1,0]]
}
paint(t){
if(t > this.point_array.length){
console.log(this.paintColor);
}else{
for(let i = 0; i < this.colors.length; i++){
this.paintColor[t-1] = this.colors[i];
if(this.ok(t)){
this.paint(t+1);
}
}
}
}
ok(t){
for(let i = 0; i < t; i++){
if(this.point_arc[t-1][i] === 1){
if(this.paintColor[t-1] === this.paintColor[i]){
return false;
}
}
}
return true;
}
};
let pic = new tu();
pic.create();
pic.paint(1);