Project Euler #83: Path sum: four ways

  • + 0 comments

    Same as DonaldJohnson191 but using arrays rather than dictionaries. Probably slower.

    import heapq
            
    N = int(input())
    weight = []
    for _ in range(N):
        weight.append([int(d) for d in input().split(" ")])
    dist = [[float('inf') for _ in range(N)] for _ in range(N)]
    
    dist[0][0] = weight[0][0]
    
    q = [(dist[0][0], (0, 0))]
    heapq.heapify(q)
    
    while q:
        d, v = heapq.heappop(q)
        
        if d > dist[v[1]][v[0]]:
            continue
        
        if v[0] > 0: #left
            new_d = d + weight[v[1]][v[0]-1]
            if new_d < dist[v[1]][v[0]-1]:
                dist[v[1]][v[0]-1] = new_d
                heapq.heappush(q, (new_d, (v[0]-1,v[1])))
        if v[0] < N - 1: #right
            new_d = d + weight[v[1]][v[0]+1]
            if new_d < dist[v[1]][v[0]+1]:
                dist[v[1]][v[0]+1] = new_d
                heapq.heappush(q, (new_d, (v[0]+1,v[1])))
        if v[1] > 0: #up
            new_d = d + weight[v[1]-1][v[0]]
            if new_d < dist[v[1]-1][v[0]]:
                dist[v[1]-1][v[0]] = new_d
                heapq.heappush(q, (new_d, (v[0],v[1]-1)))
        if v[1] < N - 1: #down
            new_d = d + weight[v[1]+1][v[0]]
            if new_d < dist[v[1]+1][v[0]]:
                dist[v[1]+1][v[0]] = new_d
                heapq.heappush(q, (new_d, (v[0],v[1]+1)))
                
    print(dist[-1][-1])