【发布时间】:2021-12-13 00:25:00
【问题描述】:
我试图使用启发式算法和优先级队列来解决二进制矩阵中的 leetcode 1091 最短路径。但是,我无法通过所有测试。您对我的代码中的错误有任何想法吗?
例如,输入是[[0,0,0],[1,1,0],[1,1,0]],输出应该是4。但是,我的代码得到的输出是5 . 我使用的启发式是当前节点到目标节点之间的直接距离。
class Solution {
public int shortestPathBinaryMatrix(int[][] grid) {
int side_length = grid.length;
// if the s left top corner is 1 then, no path exist and return -1
if(grid[0][0]== 1 || grid[side_length - 1][side_length - 1]== 1)
{
return -1;
}
if(side_length == 1)
{
return 1;
}
// 2D array for 8 directions
int[][] directions = new int[][]{{1,0},{-1,0},{0,1},{0,-1},{-1,-1},{-1,1},{1,-1},{1,1}};
PriorityQueue<Node> pqueue = new PriorityQueue<Node>(10, new Comparator<Node>()
{
public int compare(Node i, Node j) {
if(Double.compare(i.heuristic, j.heuristic) < 0){
return 100;
}
else
{
return -100;
}
}
});
double heuristic = e_distance(0, 0, side_length - 1, side_length - 1);
Node start_point = new Node(0, 0, heuristic);
pqueue.add(start_point);
boolean explored[][] = new boolean[side_length][side_length];
explored[0][0] = true;
int output = 1;
while(!pqueue.isEmpty())
{
Node curr_point = pqueue.poll();
int x = curr_point.x;
int y = curr_point.y;
explored[x][y] = true;
if(x == side_length - 1 && y == side_length - 1)
{
return output;
}
for(int[] successor : directions)
{
int successor_x = x + successor[0];
int successor_y = y + + successor[1];
heuristic = e_distance(successor_x, successor_y, side_length - 1, side_length - 1);
Node successor_point = new Node(successor_x, successor_y, heuristic);
if (pqueue.contains(successor_point))
{
continue;
}
if(successor_x >= 0 && successor_x < side_length && successor_y >= 0
&& successor_y < side_length && grid[successor_x][successor_y] == 0
&& !explored[successor_x][successor_y])
{
if(successor_x == side_length - 1 && successor_y == side_length - 1)
{
return output + 1;
}
pqueue.add(successor_point);
}
else
{
continue;
}
}
output++;
}
return -1;
}
public double e_distance(int x, int y, int target_x, int target_y)
{
return Math.sqrt(Math.abs(target_x - x) * Math.abs(target_x - x) + Math.abs(target_y - y)* Math.abs(target_y - y));
}
}
public class Node{
public int x;
public int y;
public double heuristic;
public Node(int x, int y, double heuristic)
{
this.x = x;
this.y = y;
this.heuristic = heuristic;
}
}
【问题讨论】:
-
问题用 [BFS] 标记。 BFS 不需要启发式算法,也不需要优先级队列。您是否正在尝试实施 Dijkstra 算法(也不需要启发式算法)?还是 A* ?
-
旁注:
Math.abs中不需要Math.abs(target_x - x) * Math.abs(target_x - x)。(target_x - x) *(target_x - x)总是积极的。
标签: java breadth-first-search shortest-path dijkstra a-star