All Paths From Source to Target LeetCode solution in JavaScript

1
/**
2
* @param {number[][]} graph
3
* @return {number[][]}
4
*/
5
const allPathsSourceTarget = function (graph) {
6
const n = graph.length;
7
const result = [];
8
const dfs = (node, path) => {
9
if (node === n - 1) {
10
result.push([...path, node]); // Add the current path to the result if we have reached the target node
11
return;
12
}
13
for (const neighbor of graph[node]) {
14
dfs(neighbor, [...path, node]); // Recursively explore all neighbors of the current node
15
}
16
};
17
dfs(0, []); // Start the DFS from the source node
18
return result;
19
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0