You signed in with another tab or window.Reload to refresh your session.You signed out in another tab or window.Reload to refresh your session.You switched accounts on another tab or window.Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: en/1-1000/797-all-paths-from-source-to-target.md
+271Lines changed: 271 additions & 0 deletions
Original file line number
Diff line number
Diff line change
@@ -354,6 +354,19 @@ Recursion is an important concept in computer science and mathematics, which ref
354
354
-**Base case**: Equivalent to the termination condition. After reaching the base case, the result can be returned without recursive calls to prevent infinite loops.
355
355
-**Recursive step**: The step by which the problem gradually approaches the "base case".
356
356
357
+
##Step by Step Solutions
358
+
359
+
1. Initialize an empty list`paths` to store all the valid paths found from source to target.
360
+
2. Define a recursive Depth-First Search (DFS) function, say`dfs`, that takes the current`node` and the`currentPath` (a list of nodes visited so far to reach the current node) as input.
361
+
3. Inside the`dfs` function:
362
+
a. Create a new path list by appending the current`node` to the`currentPath`. Let's call this`newPath`.
363
+
b. Check if the current`node` is the target node (`n - 1`, where`n` is the total number of nodes).
364
+
i. If it is the target node, it means we've found a complete path. Add`newPath` to the main`paths` list and return from this recursive call.
365
+
c. If the current`node` is not the target node, iterate through all`neighbor` nodes accessible from the current`node` (i.e., iterate through`graph[node]`).
366
+
i. For each`neighbor`, make a recursive call to`dfs` with the`neighbor` as the new current node and`newPath` as the path taken to reach it (`dfs(neighbor, newPath)`).
367
+
4. Start the process by calling the`dfs` function with the source node`0` and an empty initial path (`dfs(0, [])`).
368
+
5. After the initial`dfs` call completes, return the`paths` list containing all discovered paths.
369
+
357
370
##Complexity
358
371
359
372
- Time complexity:`Too complex`.
@@ -586,6 +599,264 @@ end
586
599
// Welcome to create a PR to complete the code of this language, thanks!
587
600
```
588
601
602
+
##Intuition 3
603
+
604
+
605
+
606
+
##Pattern of "Depth-First Search"
607
+
608
+
**Depth-First Search (DFS)** is a classic graph traversal algorithm characterized by its**"go as deep as possible"** approach when exploring branches of a graph. Starting from the initial vertex, DFS follows a single path as far as possible until it reaches a vertex with no unvisited adjacent nodes, then backtracks to the nearest branching point to continue exploration. This process is implemented using**recursion** or an**explicit stack (iterative method)**, resulting in a**Last-In-First-Out (LIFO)** search order. As a result, DFS can quickly reach deep-level nodes far from the starting point in unweighted graphs.
609
+
610
+
**Comparison with BFS**:
611
+
612
+
1.**Search Order**: DFS prioritizes depth-wise exploration, while Breadth-First Search (BFS) expands layer by layer, following a**First-In-First-Out (FIFO)** queue structure.
613
+
2.**Use Cases**: DFS is better suited for strongly connected components or backtracking problems (e.g., finding all paths in a maze), whereas BFS excels at finding the shortest path (in unweighted graphs) or exploring neighboring nodes (e.g., friend recommendations in social networks).
614
+
615
+
**Unique Aspects of DFS**:
616
+
617
+
-**Incompleteness**: If the graph is infinitely deep or contains cycles (without visited markers), DFS may fail to terminate, whereas BFS always finds the shortest path (in unweighted graphs).
618
+
-**"One-path deep-dive"** search style makes it more flexible for backtracking, pruning, or path recording, but it may also miss near-optimal solutions.
619
+
620
+
In summary, DFS reveals the vertical structure of a graph through its depth-first strategy. Its inherent backtracking mechanism, combined with the natural use of a stack, makes it highly effective for path recording and state-space exploration. However, precautions must be taken to handle cycles and the potential absence of optimal solutions.
621
+
622
+
##Step by Step Solutions
623
+
624
+
1. Initialize an empty list`paths` to store all valid paths found from the source to the target.
625
+
2. Create a mutable list`path` to track the current path being explored, initially containing only the source node`0`.
626
+
3. Implement a recursive DFS function that explores paths using backtracking:
627
+
- Base case: If the current node is the target node (`n-1`), make a copy of the current path and add it to the`paths` list.
628
+
- Recursive step: For each neighbor of the current node:
629
+
- Add the neighbor to the current path.
630
+
- Recursively call the DFS function with this neighbor.
631
+
- After the recursive call returns, remove the neighbor from the path (backtrack).
632
+
4. Start the DFS from the source node`0`.
633
+
5. Return the collected`paths` after the DFS completes.
path = path[:len(path) -1]// Important - backtrack
816
+
}
817
+
}
818
+
819
+
dfs(0)
820
+
821
+
return paths
822
+
}
823
+
```
824
+
825
+
##Ruby
826
+
827
+
```ruby
828
+
#@param {Integer[][]} graph
829
+
#@return {Integer[][]}
830
+
defall_paths_source_target(graph)
831
+
@paths= []
832
+
@graph= graph
833
+
@path= [0]# Important - start with node 0
834
+
835
+
dfs(0)
836
+
837
+
@paths
838
+
end
839
+
840
+
defdfs(node)
841
+
if node==@graph.length-1# Base case
842
+
@paths<<@path.clone# Important - make a copy
843
+
return
844
+
end
845
+
846
+
@graph[node].eachdo |neighbor|# Recursive step
847
+
@path<< neighbor# Important
848
+
dfs(neighbor)
849
+
@path.pop# Important - backtrack
850
+
end
851
+
end
852
+
```
853
+
854
+
##Other languages
855
+
856
+
```java
857
+
// Welcome to create a PR to complete the code of this language, thanks!
858
+
```
859
+
589
860
Dear LeetCoders! For a better LeetCode problem-solving experience, please visit website[LeetCodePython.com](https://leetcodepython.com): Dare to claim the best practices of LeetCode solutions! Will save you a lot of time!
590
861
591
862
Original link:[797. All Paths From Source to Target - LeetCode Python/Java/C++/JS code](https://leetcodepython.com/en/leetcode/797-all-paths-from-source-to-target).