Skip to content
Advertisement

Question with regard leetcode 1091 Shortest Path in Binary Matrix

I was trying to use heuristics and priority queue to solve the leetcode 1091 Shortest Path in Binary Matrix. However, I cannot pass all the tests. Do you have any idea about the error in my code?

For example, the input is [[0,0,0],[1,1,0],[1,1,0]], the output should be 4. But, my code gets the output of 5. The heuristics I used were the direct distance between the current node to the target node.

JavaScript
JavaScript

Advertisement

Answer

The following is a BFS solution based on your code. It is working although it may need further debugging :

JavaScript

A somewhat better impelementation of shortestPathBinaryMatrix :

JavaScript

When different edjges have different cost (weighted graph) you may want to implement Dijkstra algorithm. Dijkstra algorithm is basically an enhanced BFS. This is where cost and PriorityQueue are needed.
shortestPathBinaryMatrix becomes:

JavaScript

A heuristic is needed when you implement A* algorithm. A* algorithm is basically an enhanced Dijkstra algorithm.
To implement it you only need to modify the cost calculation to:
double cost = curr_point.cost+1 + heuristic ; soshortestPathBinaryMatrix becomes:

JavaScript

and distance is defined as:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement