finding all possible paths between a source node to a destination node

2 Ansichten (letzte 30 Tage)
biswajita lenka
biswajita lenka am 21 Dez. 2011
Beantwortet: BhaTTa am 19 Jan. 2024
i am trying to write code for finding all possible routing paths from a source to a destination using matlab 7.here source and destination will be selected randomly at run time.i am new in matlab.can anybody help me?

Antworten (1)

BhaTTa
BhaTTa am 19 Jan. 2024
Hey @biswajita lenka ,To find all possible routing paths from a source to a destination in a graph, you can use Depth-First Search (DFS) algorithm.
Here's a simple example of how you could implement this in MATLAB. This code assumes that you have an adjacency matrix A that represents your graph, where A(i, j) = 1 if there is a direct path from node i to node j, and A(i, j) = 0 otherwise.
function paths = findAllPaths(A, source, destination)
% Initialize paths and the stack with the starting node
paths = {};
stack = {source};
% The recursive helper function to find paths
function findPathsRecursive(currentNode, path)
% Add the current node to the path
newPath = [path currentNode];
% If the destination is reached, add the path to the paths
if currentNode == destination
paths{end+1} = newPath;
else
% Otherwise, continue to the adjacent nodes that are not yet visited
for nextNode = 1:size(A, 2)
if A(currentNode, nextNode) && ~ismember(nextNode, newPath)
findPathsRecursive(nextNode, newPath);
end
end
end
end
% Start the recursive search from the source node
findPathsRecursive(source, []);
% If no path is found, return an empty array
if isempty(paths)
paths = {};
end
end
Hope it helps.

Kategorien

Mehr zu Graph and Network Algorithms finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by