function [d,p] = dijkstra(adjList, v, mask)
% Dijkstra's algorithm to find shortest paths from v to every other vertex
% mask tells which outputs we don't care about so we can stop early.
% Based on http://www.pads.uwaterloo.ca/Bruno.Preiss/books/opus5/html/page565.html#SECTION0017411000000000000000

if (length(mask)==0),
	mask = 1:size(adjList,1);
end

k = zeros(size(adjList,1),1);
d = ones(size(adjList,1),1)*Inf;
d(v) = 0;
p = -ones(size(adjList,1),1);
while (sum(~k(mask))),
	ind = find(~k);
	[y,i] = min(d(ind));
	i = ind(i);
	k(i) = 1;
	adj = adjList(i,:);
	adj = adj(find(adj>=0));	% discard '-1' (empty) entries
	improved = (~k(adj)) & ((d(i)+1)<d(adj));
	%disp(sprintf('dist from %d to %d is %d', v, i, d(i)));
	p(adj(improved)) = i;
	d(adj(improved)) = d(i)+1;
end
