matlabスタック最適化を実現するディジェストラアルゴリズム


ディジェストラアルゴリズムの詳細なアルゴリズムは私はあまり比べていません.私は怠け者です.ネット上にmatlab版のスタック最適化されていないようなディジェストラを見て、いっそ自分で書いた.
スタックも自分で書いたので、詳しくは私の別の文章を参照してください.https://blog.csdn.net/shengsikandan/article/details/105396751.
コードは、構造の最小スタックとしてセル配列を使用し、c++のようなvector容器をセル配列を使用して実現する技術を含む.
D = [ [0,12,inf,inf,inf,16,14],       %    
        [12,0,10,inf,inf,7,inf],
        [inf,10,0,3,5,6,inf],
        [inf,inf,3,0,4,inf,inf],
        [inf,inf,5,4,0,2,8],
        [16,7,6,inf,2,0,9],
        [14,inf,inf,inf,8,9,0]
      ];
n = 7;

% --------------------------------------------------------------
%   node    ,         ,      。
%          ,         i(   i )   
node = {};
for i = 1:n
    k = 1;
    for j = 1:n
        if D(i,j) < inf && D(i,j) ~=0
            node{i,k} = {j;D(i,j)};
            k = k + 1;
        end
    end
end
% --------------------------------------------------------------

dis = ones(n)*inf;   %          ;

% --------------------------------------------------------------
%                             
%s = 6;
for s = 1:n
    dis(s,s) = 0;
    hp = make_heap({});           %      
    hp = push(hp,s,0);       
    while ~isempty(hp)
        tmpid = cell2mat(hp{1}(1));
        tmpd = cell2mat(hp{1}(2));
        hp = pop(hp);
        i = 1;
        n = length({node{tmpid,:}});
        while i <= n && ~isempty(cell2mat(node{tmpid,i}))
            pos = cell2mat(node{tmpid,i}(1));
            ds = tmpd + cell2mat(node{tmpid,i}(2));
            if dis(s,pos) > ds
                dis(s,pos) = ds;
                hp = push(hp,pos,ds);
            end
            i = i + 1;
        end
    end  
end
% --------------------------------------------------------------
dis

function a = swap(a,i,j)  %          
    t = a{i};
    a{i} = a{j};
    a{j} = t;
end

%       
function a = shiftdown(a,i)
    n = length(a);
    if 2*i <= n && 2*i+1 <= n && i <= n
        if cell2mat(a{i}(2)) > cell2mat(a{2*i}(2))
            a = swap(a,i,2*i);
            a = shiftdown(a,2*i);
        end
        if cell2mat(a{i}(2)) > cell2mat(a{2*i+1}(2))
            a = swap(a,i,2*i+1);
            a = shiftdown(a,2*i+1);
        end
    elseif 2*i <= n
        if cell2mat(a{i}(2)) > cell2mat(a{2*i}(2))
            a = swap(a,i,2*i);
            a = shiftdown(a,2*i);
        end
    end
end
%        
function a = make_heap(a)   
    n = length(a);
    for i = n/2:-1:1
        a = shiftdown(a,i);
    end
end

%       
function a = pop(a)
    a(1) = [];
    n = length(a);
    a = shiftdown(a,1);
end

%      
function a = push(a,id,value)
    n = length(a)+1;
    a{n} = {id;value};
    n = length(a);
    while n>=2
        parent = floor(n/2);
        if cell2mat(a{n}(2)) < cell2mat(a{parent}(2))
            a = swap(a,parent,n);
        end
        n = parent;
    end
end


白買はいいですね.ありがとうございます.