Bootstrap

边染色算法的matlab程序详解

#################本文为学习《图论算法及其MATLAB实现》的学习笔记#################

  • 算法用途

给出简单图的染色数尽可能少的边染色方案

  • 算法思想

1) 从图的任意一条边染色,然后找到一条与其不相邻的边进行染色,再找与两条染色边都不相邻的一条边进行染色,直到没有可以染色的边为止;

2) 再找一条没有染色的边重复上述过程。

  • 程序参数说明

M: 任意图的邻接矩阵; 

k: 染色数

C: 染色方案

  • 算法的matlab程序详解
function [k,C] = edgecodf(M)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% 边染色算法 %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% 输入:     M: 邻接矩阵; 
%%%%%%%%% 输出:     k: 染色数
%%%%%%%%%            C: 染色方案
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

W = M;
n = size(M,1);              % 得到 M 的行数
W2 = W;
for i = 1:n
    for j = 1:(i-1)
        W(i,j) = 0;         % 使 W 主对角线下三角区元素全为零
    end
end
es = sum(sum(W));           % es 为 W 的总边数

C = zeros(1,es);
k = 1;                      % 初始待染色号为 1 色
Wm = W;
for i = 1:n
    for j = (i+1):n
        if W(i,j) ~= 0
            W1 = W;
            a1 = sum(sum(Wm(1:(i-1),:))); % a1 为 Wm 第1到i-1行的所有元素和
            a2 = sum(Wm(i,1:j));          % a2 为 Wm 第i行第1到i+1列的元素和
            a = a1 + a2;
            C(a) = k;                     % 将边 a 染色为 k
            W(i,j) = 0;
            W1(i,:) = 0;W1(j,:) = 0;      % 将 W1 的第i行和第j行元素变为0
            W1(:,i) = 0;W1(:,j) = 0;      % 将 W1 的第i列和第j列元素变为0
            while sum(sum(W1))
                %%%%%%%%%%%%% 找到矩阵中一个不为 0 的坐标 %%%%%%%%%%%%%
                [k1,k2] = seekco(W1);
                a1 = sum(sum(Wm(1:(k1-1),:)));% a1 为 Wm 第1到k1-1行的所有元素和
                a2 = sum(Wm(k1,1:k2));        % a2 为 Wm 第k1行第1到k2列的元素和
                a = a1 + a2;                  % 得到与已染色的边不相邻的新边 a
                C(a) = k;                     % 将新的边 a 染色为 k
                W(k1,k2) = 0;
                W1(k1,:) = 0;W1(k2,:) = 0;    % 将 W1 的第k1行和第k2行元素变为0
                W1(:,k1) = 0;W1(:,k2) = 0;    % 将 W1 的第k1列和第k2列元素变为0
            end
            k = k+1;     % 更新待染色号 k
        end
    end
end
k = k-1;
  • 程序中子程序
function [k1,k2] = seekco(W1)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%% 找到矩阵中一个不为 0 的坐标 %%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%% 输入:     W1: 待求矩阵; 
%%%%%%%%% 输出:     k1: 非零元素的横坐标
%%%%%%%%%            k2: 非零元素的纵坐标
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

[row,col] = find(W1 ~= 0);
k1 = row(1);
k2 = col(1);
end

;