Skip to content

Commit 740c162

Browse files
author
unknown
committed
generate all paths
1 parent 8bde3dc commit 740c162

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

generateallpaths.py

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# dfs / recursively
2+
# current index -> matrix[i][j]
3+
# first check if the present index is valid
4+
# check if the current index can be explored
5+
# move right , down , diagonal
6+
# else backtrack
7+
8+
def findPaths(m,path,i,j):
9+
r,c = len(m),len(m[0])
10+
# if destination is reached
11+
# print
12+
if i == r-1 and j == c-1:
13+
print(path+[m[i][j]])
14+
return
15+
16+
# explore
17+
path.append(m[i][j])
18+
19+
20+
# move down
21+
if 0 <= i+1 <= r-1 and 0 <= j <= c-1:
22+
findPaths(m,path,i+1,j)
23+
24+
25+
# move right
26+
if 0 <= i <= r-1 and 0 <= j+1 <= c-1:
27+
findPaths(m,path,i,j+1)
28+
29+
30+
# move diagonal
31+
if 0 <= i+1 <= r-1 and 0 <= j+1 <= c-1:
32+
findPaths(m,path,i+1,j+1)
33+
34+
# if none of the above is explorable or invalid index
35+
# backtrack
36+
path.pop()
37+
38+
mat = []
39+
n = int(input())
40+
for i in range(n):
41+
row = list(map(int,input().split()))
42+
mat.append(row)
43+
44+
path = []
45+
findPaths(mat,path,0,0)

shortestpath.py

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import heapq
2+
from collections import defaultdict
3+
4+
5+
def shortestPath(graph,src,dest):
6+
h = []
7+
# keep a track record of vertices with the cost
8+
# heappop will return vertex with least cost
9+
# greedy SRC -> MIN - > MIN -> MIN -> DEST
10+
11+
heapq.heappush(h,(0,src))
12+
13+
while len(h)!=0:
14+
currcost,currvtx = heapq.heappop(h)
15+
if currvtx == dest:
16+
print("Path Exisits {} to {} with cost {}".format(src,dest,currcost))
17+
break
18+
for neigh,neighcost in graph[currvtx]:
19+
heapq.heappush(h,(currcost+neighcost,neigh))
20+
21+
22+
23+
24+
graph = defaultdict(list)
25+
v,e = map(int,input().split())
26+
for i in range(e):
27+
u,v,w = map(str,input().split())
28+
graph[u].append((v,int(w)))
29+
src,dest = map(str,input().split())
30+
shortestPath(graph,src,dest)

0 commit comments

Comments
 (0)