-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem81.py
39 lines (33 loc) · 1.11 KB
/
problem81.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
'''
Find the minimal path sum from the top left to the
bottom right by moving right and down.
'''
import csv
import networkx as nx
def main():
matrix = []
with open('src/matrix.txt', 'r', encoding='utf-8') as f:
csv_reader = csv.reader(f)
for row in csv_reader:
matrix.append([int(a) for a in row])
G = nx.DiGraph()
G.add_nodes_from([(i, j) for i in range(80) for j in range(8)])
s = (-1, -1) # supersource
t = (80, 80) # supersink
G.add_nodes_from([s, t]) # supersource and supersink
G.add_edge(s, (0, 0), weight=0)
G.add_edge((79, 79), t, weight=matrix[-1][-1])
for i in range(80):
for j in range(80):
w = matrix[i][j]
if i < 79: # down
G.add_edge((i, j), (i + 1, j), weight=w)
if j < 79: # right
G.add_edge((i, j), (i, j + 1), weight=w)
return nx.single_source_dijkstra_path_length(G, source=s)[t]
if __name__ == '__main__':
import time
t1 = time.time()
print(main())
t2 = time.time()
print('{:.3f} s'.format(t2 - t1))