Path Finder 3 (Code Wars 18)

OK this series is winning me over. Cost function is just interesting enough.

def neighbors(maze, i, j):
    toTry = []
    if i > 0:
        toTry.append((i-1, j))
    if j > 0:
        toTry.append((i, j-1))
    if i + 1 < len(maze):
        toTry.append((i+1, j))
    if j + 1 < len(maze[i]):
        toTry.append((i, j+1))
    return toTry
def path_finder(maze):
    maze = maze.split()
    cost = {}
    toVisit = set([(0,0)])
    cost[(0,0)] = 0
    target = (len(maze)-1, len(maze)-1)
    while toVisit:
        i, j = toVisit.pop()
        c = cost[(i, j)]
        for (a, b) in neighbors(maze, i, j):
            d = abs(int(maze[i][j]) - int(maze[a][b])) + c
            if (a, b) not in cost:
                cost[(a, b)] = d
                toVisit.add((a, b))
            elif cost[(a, b)] > d:
                cost[(a, b)] = d
                toVisit.add((a, b))
    if target in cost:
        return cost[target]
    return False

Leave a Reply