advanced
Big-O Optimization for Graph Traversal
Critique and optimize a poorly written graph traversal algorithm to improve time and space complexity.
📝 प्रॉम्ट सामग्री
Review the following Python code snippet which implements a shortest-path finding algorithm on a weighted graph. The current implementation has a time complexity of O(V^3). Critique the inefficiencies in the current approach, specifically identifying redundant calculations or suboptimal data structures used. Refactor the code to implement Dijkstra's algorithm using a min-heap priority queue, reducing the time complexity to O(E + V log V). Additionally, modify the solution to return not just the distance, but the actual path reconstruction. Provide the optimized code and a step-by-step explanation of how the heap operations maintain the algorithm's invariant.