Azzera filtri
Azzera filtri

Hi, how to make a Djikstra and Bellman coding to show the shortest path/ ways between any nodes in the graph. For example, node 1 to node 4.

1 visualizzazione (ultimi 30 giorni)

Risposte (1)

Kush
Kush il 8 Lug 2023
You can implement the dijkstra function like this and replace the sample adjacency matrix with your network to get the shortest path from one node to other.
function dijkstraAlgo(adjMatrix, source, destination)
% Number of nodes in the graph
numNodes = size(adjMatrix, 1);
% Initialize distance array with infinity
distance = inf(1, numNodes);
% Initialize visited array
visited = false(1, numNodes);
% Initialize previous node array
prevNode = zeros(1, numNodes);
% Set distance of source node to 0
distance(source) = 0;
% Dijkstra's algorithm
for i = 1:numNodes
minDist = min(distance(~visited));% Find the node with the minimum distance
currentNode = find(distance == minDist & ~visited, 1);
visited(currentNode) = true;% Mark the current node as visited
% Check neighbors of the current node
for j = 1:numNodes
if adjMatrix(currentNode, j) > 0
% Calculate the new distance
newDist = distance(currentNode) + adjMatrix(currentNode, j);
% Update the distance and previous node if a shorter path is found
if newDist < distance(j)
distance(j) = newDist;
prevNode(j) = currentNode;
end
end
end
end
% Display the shortest path and its distance
if distance(destination) == inf
disp('No path found.');
else
path = [destination];
while path(1) ~= source
path = [prevNode(path(1)), path];
end
disp(['Shortest path: ' num2str(path)]);
disp(['Distance: ' num2str(distance(destination))]);
end
end
% Replace your adjacency matrix representing a graph
adjMatrix = [0 2 4 0 0;
2 0 1 4 0;
4 1 0 2 3;
0 4 2 0 1;
0 0 3 1 0];
source = 1; % set the source node
destination = 5; % set the destination node
dijkstraAlgo(adjMatrix, source, destination);

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by