我有一个8x8的棋盘。这是我得到的信息:
- 国王的坐标 - 目标的坐标 - 被阻挡的方格数量 - 被阻挡的方格的坐标
我不能踩在被阻挡的方格上。我想找到到达目标的最短路径,如果没有可用的路径(即目标不可达),则返回-1。
我试着写代码,但我不确定代码是否有意义,而且我有点迷失方向,非常感谢任何帮助。
- 国王的坐标 - 目标的坐标 - 被阻挡的方格数量 - 被阻挡的方格的坐标
我不能踩在被阻挡的方格上。我想找到到达目标的最短路径,如果没有可用的路径(即目标不可达),则返回-1。
我试着写代码,但我不确定代码是否有意义,而且我有点迷失方向,非常感谢任何帮助。
Program ShortestPath;
TYPE
coords = array [0..1] of integer;
var goal,shortest : coords;
currentX, currentY,i : integer;
arrBlocked,result : array [0..64] of coords;
function findShortestPath (currentX, currentY, goal, arrBlocked,path,i) : array [0..64] of coords;
begin
{check if we are still on board}
if (currentX < 1 OR currentX > 8 OR currentY < 1 OR currentY > 8) then begin
exit;
end;
if (currentX = arrBlocked[currentX] AND currentY = arrBlocked[currentY]) then begin
exit;
end;
{save the new square into path}
path[i] = currentX;
path[i+1] = currentY;
{check if we reached the goal}
if (currentX = goal[0]) and (currentY = goal[1]) then begin
{check if the path was the shortest so far}
if (shortest > Length(path)) then begin
shortest := Length(path);
findShortestPath := path;
end else begin
exit;
end;
end else begin
{move on the board}
findShortestPath(currentX+1, currentY, goal, arrBlocked,path,i+2);
findShortestPath(currentX, currentY+1, goal, arrBlocked,path,i+2);
findShortestPath(currentX-1, currentY, goal, arrBlocked,path,i+2);
findShortestPath(currentX, currentY-1, goal, arrBlocked,path,i+2);
end;
end;
begin
{test values}
currentX = 2;
currentY = 5;
goal[0] = 8;
goal[1] = 7;
arrBlocked[0] = [4,3];
arrBlocked[1] = [2,2];
arrBlocked[2] = [8,5];
arrBlocked[3] = [7,6];
i := 0;
shortest := 9999;
path[i] = currentX;
path[i+1] = currentY;
i := i + 2;
result := findShortestPath(currentX,currentY,goal,arrBlocked,path,i);
end.