回溯法

回溯法,是一种枚举法,就是尝试所有结果,最后得到最优解。

从初始状态出发,按照深度优先搜索的方法,根据产生子节点的条件约束,搜索问题的解。当发现当前节点不满足求解条件时,就回溯,尝试其他路径。

深度优先遍历

例子:地图着色

有一幅地图和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);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值