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

조회 수: 2 (최근 30일)
biswajita lenka
biswajita lenka 2011년 12월 21일
답변: BhaTTa 2024년 1월 19일
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?

답변 (1개)

BhaTTa
BhaTTa 2024년 1월 19일
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.

카테고리

Help CenterFile Exchange에서 Graph and Network Algorithms에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by