如何在Matlab中优化我的Dijkstra算法以减少运行时间?

时间:2016-10-22 18:02:31

标签: algorithm matlab optimization matrix

下面给出的是我的Dijkstra算法。 B矩阵是成本图。源节点是R = [1,1]并且没有目标节点。我想在给定矩阵中所有节点的源节点的情况下计算Dijkstra算法。

但我的Dijkstra跑了20多分钟。我不知道如何优化我的代码。你能帮帮我吗?

    function hMap = djikstra(B,R)

    %B = Cost Map
    %R = Initial position of the robot

    fprintf('In Dijkstra');
    hMap = Inf(length(B));              % Assigning infinity
    hMap(R(1),R(2)) = 0  ;              % source node
    open = [];
    open = [R(1),R(2),0];
    closed = [];
    closed = [closed; open(1,1:2)];     %Put current source node in closed
    x = R(1);
    y = R(2);

    while(size(open) ~= 0)    
        if(x-1 ~=0)
           if(sum(ismember(closed(:,1:2),[x-1,y],'rows'))== 0)  
             cost = hMap(x,y)+ B(x-1,y); 
             fprintf('x-1');
             %if(cost  < hMap(x-1,y) )
               hMap(x-1,y) = min(cost,hMap(x-1,y));
               fprintf(' update x-1');
               open = [open;x-1,y,hMap(x-1,y)];
             %end
           end
        end

       if(x+1 <= length(B))
          if(sum(ismember(closed(:,1:2),[x+1,y],'rows'))== 0)  
            cost = hMap(x,y)+ B(x+1,y) ;
            %if( cost < hMap(x+1,y))
              hMap(x+1,y) = min(cost,hMap(x+1,y));
              open = [open;x+1,y,hMap(x+1,y)];
            %end
          end
       end

       if(y-1 ~= 0)
         if(sum(ismember(closed(:,1:2),[x,y-1],'rows'))== 0)  
           cost = hMap(x,y)+ B(x,y-1);
           %if( cost < hMap(x,y-1))
             hMap(x,y-1) = min(cost, hMap(x,y-1));
             open = [open;x,y-1,hMap(x,y-1)] ;
           %end
       end
      end

     if(y+1 <= length(B))
       if(sum(ismember(closed(:,1:2),[x,y+1],'rows'))== 0)  
         cost = hMap(x,y)+ B(x,y+1);
         %if(cost< hMap(x,y+1))
           hMap(x,y+1) = min(cost,hMap(x,y+1));
           open = [open;x,y+1,hMap(x,y+1)];
         %end
       end
     end

     closed = [closed;x,y];
     open = open(2:size(open,1),:);                 %Removing source element from the open list
     open = unique(open,'rows');
     open = sortrows(open,3);                       % Sorting w.r.t G Value

     fprintf('------------------------------OPEN--------------------------')
     open

     if(size(open) ~= 0)
     x = open(1,1)
     y = open(1,2)
     end

    end
end

0 个答案:

没有答案