Project Euler #83: Path sum: four ways

  • + 0 comments

    This is perfect python code using dijkstra algorithm.

    import heapq
    
    def matrix_to_weighted_graph(matrix):
        rows, cols = len(matrix), len(matrix[0])
        graph = {}
        
        for i in range(rows):
            for j in range(cols):
                node = (i, j)  # Each element is a node
                neighbors = {}
                
                # Check and add valid neighbors with weights (value of neighboring element)
                if i > 0:  # Up
                    neighbors[(i-1, j)] = matrix[i-1][j]
                if i < rows - 1:  # Down
                    neighbors[(i+1, j)] = matrix[i+1][j]
                if j > 0:  # Left
                    neighbors[(i, j-1)] = matrix[i][j-1]
                if j < cols - 1:  # Right
                    neighbors[(i, j+1)] = matrix[i][j+1]
                
                graph[node] = neighbors
        graph[(cols-1, rows-1)] = {}
        return graph
        
    
    def dijkstra(graph, source, target):
        # Initialize distances and priority queue
        distances = {vertex: float('infinity') for vertex in graph}
        distances[source] = 0
        priority_queue = [(0, source)]  # (distance, vertex)
        
        while priority_queue:
            current_distance, current_vertex = heapq.heappop(priority_queue)
            
            # Skip if the distance is outdated
            if current_distance > distances[current_vertex]:
                continue
            
            for neighbor, weight in graph[current_vertex].items():
                distance = current_distance + weight
                # If a shorter path is found
                if distance < distances[neighbor]:
                    distances[neighbor] = distance
                    heapq.heappush(priority_queue, (distance, neighbor))
        
        return distances[target]
        
    T = int(input())
    matrix = []
    for i in range(T):
        line = list(map(int, input().split()))
        matrix.append(line)
        
    rows, cols = len(matrix), len(matrix[0])
    
    graph = matrix_to_weighted_graph(matrix)
    length = matrix[0][0] + dijkstra(graph, (0,0), (rows - 1, cols - 1))
    print(length)