Leetcode Problem 2662. Minimum Cost of a Path With Special Roads
2662. Minimum Cost of a Path With Special Roads
Leetcode Solutions
Dijkstra's Algorithm with Priority Queue
Create a graph representation where each node corresponds to a point in space (start, target, and endpoints of special roads).
Add edges between nodes to represent the cost of using a special road or the Manhattan distance if walking directly.
Initialize a priority queue and add the starting node with a cost of 0.
While the priority queue is not empty:
a. Pop the node with the minimum cost from the queue.
b. If this node is the target, return the cost as the result.
c. For each neighbor of the current node, calculate the cost to reach that neighbor.
d. If the calculated cost is less than the known cost to reach the neighbor, update the cost and add the neighbor to the priority queue.
If the target is not reached, return -1 indicating no path exists.
Breadth-First Search (BFS) with Special Road Optimization