summaryrefslogtreecommitdiff
path: root/083.py
diff options
context:
space:
mode:
authorReiner Herrmann <reiner@reiner-h.de>2014-08-31 20:21:45 +0200
committerReiner Herrmann <reiner@reiner-h.de>2014-08-31 20:35:09 +0200
commit95341b61b030c9e1290f3b326cb7ec584f543aea (patch)
tree852386fa04d32eb859bca11c0eff7b5ef9e50f00 /083.py
parent571164d977f91925c4c76a292f74f5f93d09ae23 (diff)
moved files to higher directory after split to new repositoryHEADtrunk
Diffstat (limited to '083.py')
-rw-r--r--083.py76
1 files changed, 76 insertions, 0 deletions
diff --git a/083.py b/083.py
new file mode 100644
index 0000000..f1620e5
--- /dev/null
+++ b/083.py
@@ -0,0 +1,76 @@
+
+# uses Dijkstra's algorithm to find minimal path
+# (based on solution for problem 81)
+
+infinity = 999999
+
+matrix = []
+
+width = 80
+height = 80
+
+f = open('083.txt', 'r')
+for line in f:
+ line.rstrip('\n')
+ line_str = line.split(',')
+ line_int = [ int(x) for x in line_str ]
+ matrix.append(line_int)
+f.close()
+
+
+# initialize
+distance = [infinity] * (width*height)
+pre = [None] * (width*height)
+distance[0] = 0
+Q = range(width*height)
+
+def mindistance(Q):
+ mind = infinity
+ mini = -1
+ for i in Q:
+ if distance[i] < mind:
+ mind = distance[i]
+ mini = i
+ return mini
+
+def neighbors(u):
+ n = []
+ row = u / width
+ col = u % width
+ if col < width-1:
+ n.append(row*width + col + 1) # right neighbor
+ if row < height-1:
+ n.append((row+1)*width + col) # lower neighbor
+ if row > 0:
+ n.append((row-1)*width + col) # upper neighbor
+ if col > 0:
+ n.append(row*width + col - 1) # left neighbor
+ return n
+
+def update(u, v):
+ alt = distance[u] + matrix[v/width][v%width]
+ if alt < distance[v]:
+ distance[v] = alt
+ pre[v] = u
+
+# main algorithm
+while len(Q) > 0:
+ u = mindistance(Q)
+ Q.remove(u)
+ for v in neighbors(u):
+ if v in Q:
+ update(u, v)
+
+# search min distance
+u = width*height-1 # target node
+path = [ u ]
+while pre[u] != None:
+ u = pre[u]
+ path = [u] + path
+
+minsum = 0
+for n in path:
+ minsum += matrix[n/width][n%width]
+
+print minsum
+