djiskas algorithm in matlab

Here's an implementation of Djisktra's algorithm in MATLAB for finding the shortest path between two nodes in a graph.

main.m
function [ path, dist ] = djisktra( graph, start_node, end_node )
%DJISKTRA finds the shortest path in a graph using Djisktra's algorithm
%   Inputs:
%       graph: a weighted adjacency matrix representing the graph
%       start_node: the node to start from
%       end_node: the node to end at
%   Outputs:
%       path: an array of node indices representing the shortest path
%       dist: the total path distance

    num_nodes = size(graph, 1);
    visited = zeros(num_nodes, 1);
    dist = Inf(num_nodes, 1);
    prev = zeros(num_nodes, 1);
    dist(start_node) = 0;

    while sum(visited) < num_nodes
        [~, current] = min(dist + 1e9 * visited);
        visited(current) = 1;

        for i = 1:num_nodes
            if graph(current, i) > 0
                alt = dist(current) + graph(current, i);
                if alt < dist(i)
                    dist(i) = alt;
                    prev(i) = current;
                end
            end
        end
    end

    % Build the path
    path = [];
    node = end_node;
    while node ~= start_node
        path = [node path]; %#ok<AGROW>
        node = prev(node);
    end
    path = [start_node path];
end
1171 chars
41 lines

Note that the input graph should be a weighted adjacency matrix, where the distance between nodes is represented by the weight of their edge. The algorithm returns both the shortest path as an array of node indices and the total distance traveled.

gistlibby LogSnag