56
56
<li>你可以把路径以任意顺序输出,但在路径内的结点的顺序必须保证。</li>
57
57
</ul >
58
58
59
-
60
59
## 解法
61
60
62
61
<!-- 这里可写通用的实现逻辑 -->
69
68
70
69
<!-- 这里可写当前语言的特殊实现逻辑 -->
71
70
71
+ BFS:
72
+
72
73
``` python
73
74
class Solution :
74
75
def allPathsSourceTarget (self , graph : List[List[int ]]) -> List[List[int ]]:
@@ -86,10 +87,32 @@ class Solution:
86
87
return ans
87
88
```
88
89
90
+ DFS:
91
+
92
+ ``` python
93
+ class Solution :
94
+ def allPathsSourceTarget (self , graph : List[List[int ]]) -> List[List[int ]]:
95
+ ans = []
96
+
97
+ def dfs (i , path ):
98
+ if i == len (graph) - 1 :
99
+ ans.append(path.copy())
100
+ return
101
+ for j in graph[i]:
102
+ path.append(j)
103
+ dfs(j, path)
104
+ path.pop(- 1 )
105
+
106
+ dfs(0 , [0 ])
107
+ return ans
108
+ ```
109
+
89
110
### ** Java**
90
111
91
112
<!-- 这里可写当前语言的特殊实现逻辑 -->
92
113
114
+ BFS:
115
+
93
116
``` java
94
117
class Solution {
95
118
public List<List<Integer > > allPathsSourceTarget (int [][] graph ) {
@@ -115,6 +138,98 @@ class Solution {
115
138
}
116
139
```
117
140
141
+ DFS:
142
+
143
+ ``` java
144
+ class Solution {
145
+ private List<List<Integer > > ans;
146
+ private int [][] graph;
147
+
148
+ public List<List<Integer > > allPathsSourceTarget (int [][] graph ) {
149
+ ans = new ArrayList<> ();
150
+ this . graph = graph;
151
+ List<Integer > path = new ArrayList<> ();
152
+ path. add(0 );
153
+ dfs(0 , path);
154
+ return ans;
155
+ }
156
+
157
+ private void dfs (int i , List<Integer > path ) {
158
+ if (i == graph. length - 1 ) {
159
+ ans. add(new ArrayList<> (path));
160
+ return ;
161
+ }
162
+ for (int j : graph[i]) {
163
+ path. add(j);
164
+ dfs(j, path);
165
+ path. remove(path. size() - 1 );
166
+ }
167
+ }
168
+ }
169
+ ```
170
+
171
+ ### ** C++**
172
+
173
+ DFS:
174
+
175
+ ``` cpp
176
+ class Solution {
177
+ public:
178
+ vector<vector<int >> graph;
179
+ vector<vector<int >> ans;
180
+
181
+ vector<vector<int>> allPathsSourceTarget(vector<vector<int>>& graph) {
182
+ this->graph = graph;
183
+ vector<int> path;
184
+ path.push_back(0);
185
+ dfs(0, path);
186
+ return ans;
187
+ }
188
+
189
+ void dfs (int i, vector<int > path) {
190
+ if (i == graph.size() - 1)
191
+ {
192
+ ans.push_back(path);
193
+ return;
194
+ }
195
+ for (int j : graph[ i] )
196
+ {
197
+ path.push_back(j);
198
+ dfs(j, path);
199
+ path.pop_back();
200
+ }
201
+ }
202
+ };
203
+ ```
204
+
205
+ DFS:
206
+
207
+ ### **Go**
208
+
209
+ ```go
210
+ func allPathsSourceTarget(graph [][]int) [][]int {
211
+ var path []int
212
+ path = append(path, 0)
213
+ var ans [][]int
214
+
215
+ var dfs func(i int)
216
+ dfs = func(i int) {
217
+ if i == len(graph)-1 {
218
+ ans = append(ans, append([]int(nil), path...))
219
+ return
220
+ }
221
+ for _, j := range graph[i] {
222
+ path = append(path, j)
223
+ dfs(j)
224
+ path = path[:len(path)-1]
225
+ }
226
+ }
227
+
228
+ dfs(0)
229
+ return ans
230
+ }
231
+ ```
232
+
118
233
### ** ...**
119
234
120
235
```
0 commit comments