Finding Shortest Path from starting node to each other nodes using Dijkstra's

Viewed 78

This is the problem from hackerrank . I've been doing some basic graph problems. This is a undirected graph with equal weights on all edges. I have to print the weight to reach each node from the starting node. If it cannot reach, I had to return -1. I should not include the cost of the source node in the answer List

This is my solution

def bfs(n, m, edges, s):
    adjList = defaultdict(list)

    for u , v in edges:
        adjList[u].append((v , 6))
        adjList[v].append((u , 6))

    queue = []
    heapq.heappush(queue , (0,0,s))
    visited = set()
    visited.add(s)
    result = [-1] + [-1 for i in range(n)]

    while queue:
        costSoFar , travelled , nextNode = heapq.heappop(queue)
        result[nextNode] = costSoFar

        if travelled == m:
            break

        for neighbourNode , neighbourCost in adjList[nextNode]:
            if neighbourNode not in visited:
                heapq.heappush(queue , (costSoFar + 6 , travelled + 1 , neighbourNode))
                visited.add(neighbourNode) 
                   
    answer = result[ : s - 1] + result[s + 1 :]
    return answer

I know Dijkstra's is a bit overkill here and we can solve it using a simple BFS. But I wanted to practise this. Thats the reason I tried to implement Dijkstra's.

The problem is, I am able to pass the sample cases but its giving me TLE and WA for other cases. Could someone tell, where in this I am going wrong and correct the code with this same implementation.

0 Answers
Related