问题描述
我的通信室友请我帮她写一个算法我发现还挺麻烦 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
方案------方案