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

2 views (last 30 days)
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?

Answers (1)

BhaTTa
BhaTTa on 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.

Categories

Find more on Search Path in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!