-
-
Save anonymous/92033633c26cf9fb4b10 to your computer and use it in GitHub Desktop.
Minimal traverse distance within a matrix
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy | |
y = numpy.zeros((3, 3)) | |
def findLeastPath(matrix, row=0, column=0, path=[], sum_=0): | |
row_max = matrix.shape[0] | |
column_max = matrix.shape[1] | |
if column == column_max - 1 and row == row_max - 1: | |
y[row][column] = matrix[row][column] | |
return matrix[row][column] + sum_ | |
else: | |
current_cost = matrix[row][column] | |
path.append((row, column, current_cost)) | |
if column == column_max - 1: | |
if y[row+1][column] != 0: | |
y[row][column] = current_cost + y[row+1][column] | |
return current_cost + y[row+1][column] | |
else: | |
down = findLeastPath(matrix, row + 1, column, path, sum_ + current_cost) | |
y[row][column] = current_cost + y[row+1][column] | |
return down | |
elif row == row_max - 1: | |
if y[row][column+1] != 0: | |
y[row][column] = current_cost + y[row][column + 1] | |
return current_cost + y[row][column + 1] | |
else: | |
right = findLeastPath(matrix, row, column + 1, path, sum_ + current_cost) | |
y[row][column] = current_cost + y[row][column + 1] | |
return right | |
else: | |
if y[row][column + 1] != 0: | |
right = y[row][column + 1] + current_cost | |
else: | |
findLeastPath(matrix, row, column + 1, path, sum_ + current_cost) | |
right = y[row][column + 1] + current_cost | |
if y[row + 1][column] != 0: | |
down = y[row + 1][column] + current_cost | |
else: | |
findLeastPath(matrix, row + 1, column, path, sum_ + current_cost) | |
down = y[row+1][column] + current_cost | |
if y[row + 1][column + 1] != 0: | |
diagonal = y[row + 1][column + 1] + current_cost | |
else: | |
findLeastPath(matrix, row + 1, column + 1, path, sum_ + current_cost) | |
diagonal = y[row+1][column+1] + current_cost | |
#print right | |
#print down | |
#print diagonal | |
min_val = min(right, down, diagonal) | |
y[row][column] = min_val | |
return min_val | |
if __name__ == "__main__": | |
x = numpy.random.random((3, 3)) | |
print x | |
print findLeastPath(x) | |
print y |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment