Skip to content

Commit 0677112

Browse files
committed
Added dfs solution with back tracking
1 parent 1ef98fa commit 0677112

1 file changed

Lines changed: 37 additions & 0 deletions

File tree

AllPathsFromSourceToTarget.py

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
#All Paths From Source to Target
2+
#https://leetcode.com/problems/all-paths-from-source-to-target/description/
3+
4+
class dfs(object):
5+
def __init__(self, input_matrix):
6+
self.input_matrix = input_matrix
7+
8+
def solution(self, source, destination, path):
9+
if source == destination:
10+
print path
11+
return
12+
for next_node in self.input_matrix[source]:
13+
path.append(next_node)
14+
self.solution(next_node, destination, path)
15+
#Back track
16+
path.pop()
17+
'''
18+
Cannot really thik of a way to do it in bfs
19+
class bfs(object):
20+
def __init__(self, input_matrix):
21+
self.input_matrix = input_matrix
22+
23+
def solution(self, source, destination, path):
24+
q = []
25+
q.append(source)
26+
path = []
27+
while q:
28+
top - = q.pop(0)
29+
if(top == destination):
30+
print path
31+
continue
32+
'''
33+
34+
#Main Program
35+
matrix = [[1,2], [3], [3], []]
36+
obj = dfs(matrix)
37+
obj.solution(0, 3, [0])

0 commit comments

Comments
 (0)