多点m着色算法-回溯

多点m着色算法-回溯

问题描述

我的通信室友请我帮她写一个算法我发现还挺麻烦 mark一下
图的m着色问题。给定无向连通图G和m种颜色,用这些颜色给图的顶点着色,每个顶点一种颜色。如果要求G的每条边的两个顶点着不同颜色。给出所有可能的着色方案;如果不存在,则回答“NO”。

实现

% --- 回溯算法实现m可着色 ---
clc;
clear all;
close all;
% graph = [                     % 共A、B、C、D、E、F、G、H,8个点的图
% %   A B C D E F G H    
% 0 1 1 1 0 0 1 0;          % A
% 1 0 1 1 1 0 0 0;          % B
% 1 1 0 0 1 1 1 0;          % C
% 1 1 0 0 1 0 1 0;          % D
% 0 1 1 1 0 1 1 1;          % E
% 0 0 1 0 1 0 0 1;          % F
% 1 0 1 1 1 0 0 1;          % G
% 0 0 0 0 1 1 1 0;          % H
% ];
graph=[
    0 1 ;
    1 0 ;
    ];
colorNum=3;
vnum = max(size(graph));
colorTbl = zeros(1, vnum); %表示当前染色情况
index=0;
res=true;
sear(index,graph,colorTbl,vnum,colorNum,res);

function sear(index,graph,colorTbl,vnum,colorNum,res)
    for i=1:index
        if colorTbl(index)==colorTbl(i) && graph(index,i)==1 %当两个节点是连同并且颜色一样
            res=false;
            break;
        end
        res=true;
    end
    if(res)
        if(index==vnum)
            for i=1:index
               disp(colorTbl(i));
            end
            disp("方案------方案");
        else
            for i=1:colorNum
                colorTbl(index+1)=i;
                sear(index + 1,graph,colorTbl,vnum,colorNum,res);
            end
        end
    end
end

结果

 1

 2

方案------方案
1

 3

方案------方案
2

 1

方案------方案
2

 3

方案------方案
3

 1

方案------方案
3

 2

方案------方案


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值