Skip to content

Commit 9004d8d

Browse files
committed
Add solution #797
1 parent a3ff7e5 commit 9004d8d

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -607,6 +607,7 @@
607607
794|[Valid Tic-Tac-Toe State](./0794-valid-tic-tac-toe-state.js)|Medium|
608608
795|[Number of Subarrays with Bounded Maximum](./0795-number-of-subarrays-with-bounded-maximum.js)|Medium|
609609
796|[Rotate String](./0796-rotate-string.js)|Easy|
610+
797|[All Paths From Source to Target](./0797-all-paths-from-source-to-target.js)|Medium|
610611
802|[Find Eventual Safe States](./0802-find-eventual-safe-states.js)|Medium|
611612
804|[Unique Morse Code Words](./0804-unique-morse-code-words.js)|Easy|
612613
819|[Most Common Word](./0819-most-common-word.js)|Easy|
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* 797. All Paths From Source to Target
3+
* https://leetcode.com/problems/all-paths-from-source-to-target/
4+
* Difficulty: Medium
5+
*
6+
* Given a directed acyclic graph (DAG) of n nodes labeled from 0 to n - 1, find all possible paths
7+
* from node 0 to node n - 1 and return them in any order.
8+
*
9+
* The graph is given as follows: graph[i] is a list of all nodes you can visit from node i (i.e.,
10+
* there is a directed edge from node i to node graph[i][j]).
11+
*/
12+
13+
/**
14+
* @param {number[][]} graph
15+
* @return {number[][]}
16+
*/
17+
var allPathsSourceTarget = function(graph) {
18+
const target = graph.length - 1;
19+
const paths = [];
20+
21+
const dfs = (node, path) => {
22+
if (node === target) {
23+
paths.push([...path]);
24+
return;
25+
}
26+
27+
for (const neighbor of graph[node]) {
28+
path.push(neighbor);
29+
dfs(neighbor, path);
30+
path.pop();
31+
}
32+
};
33+
34+
dfs(0, [0]);
35+
return paths;
36+
};

0 commit comments

Comments
 (0)