Вы можете посетить все узлы и опустить узлы, которые уже посещены.
Рекурсивный подход:
function getRoutes(routes, start, end) {
function go(node, visited = []) {
visited.push(node);
if (node === end) {
result.push(visited);
return;
}
routes[node].forEach(n => {
if (visited.includes(n)) return;
go(n, [...visited]);
});
}
var result = [];
go(start);
return result;
}
const routes = { 0: [1, 2, 3], 1: [8, 6, 4], 2: [7, 8, 3], 3: [8, 1], 4: [6], 5: [8, 7], 6: [9, 4], 7: [4, 6], 8: [1], 9: [1, 4] };
getRoutes(routes, 0, 9).forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Итерационный подход со стеком:
function getRoutes(routes, start, end) {
var stack = [[start, []]],
result = [];
while (stack.length) {
const [node, visited] = stack.shift();
visited.push(node);
if (node === end) {
result.push(visited);
continue;
}
for (const n of routes[node]) {
if (visited.includes(n)) continue;
stack.push([n, [...visited]]);
}
}
return result;
}
const routes = { 0: [1, 2, 3], 1: [8, 6, 4], 2: [7, 8, 3], 3: [8, 1], 4: [6], 5: [8, 7], 6: [9, 4], 7: [4, 6], 8: [1], 9: [1, 4] };
getRoutes(routes, 0, 9).forEach(a => console.log(...a));
.as-console-wrapper { max-height: 100% !important; top: 0; }