import java.util.*;
public class path1 {
public static void main(String[] args) {
//Maze design 1 indicate a cell with obstacles
int[][] grid = new int[][]{{0, 0, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0}, {0, 0, 0, 0, 1, 0}, {0, 0, 1, 1, 1, 0}, {0, 0, 0, 0, 1, 0}};
//Initial position of the Robot
int[] init = new int[]{0, 0};
//Goal position of the Robot
int[] goal = new int[]{grid.length - 1, grid[0].length - 1};
//The cost function which is initially defined as 1
int cost = 1;
//Movement of a robot(-1,0)->up,(0,-1)->left,(1,0)->down,(0,1)->right
int[][] delta = new int[][]{{-1, 0}, {0, -1}, {1, 0}, {0, 1}};
path1 a =new path1();
a.search(init,goal,grid,delta,cost);
}
public static int[] search(int[]init,int [] goal,int[][] grid,int[][] delta,int cost) {
int[][] closed = new int[5][6];
closed[init[0]] [init[1]]=1;
int x=init[0];
int y = init[1];
int g=0;
ArrayList <Integer>open= new ArrayList<Integer>();
open.add(g);
open.add(x);
open.add(y);
boolean found=false;
boolean resign=false;
while (!found && !resign) {
if (open.size() == 0) {
resign = true;
System.out.println("Fail");
} else {
Collections.sort(open);
Collections.reverse(open);
Collection.pop(open);//I think error in this line as java arraylist cannot allow pop function but I have to pop the last element from the list and remove it from list. So how can I do that?
x = open.get(1);
y = open.get(2);
g = open.get(0);
}
if(x==goal[0]&& y==goal[1]){
found=true;
System.out.println(x);
System.out.println(y);
System.out.println(g);
System.out.println("Search Successful");
}
else{
for (int i=0;i<delta.length;i++){
int x2=x+delta[i][0];
int y2=y+delta[i][1];
if(x2>=0 && x2<grid.length && y2>=0 && y2<grid[0].length){
if(closed[x2][y2]==0 && grid[x2][y2]==0){
int g2= g+cost;
open.add(g2);
open.add(x2);
open.add(y2);
System.out.println("Now g2 is"+g2);
System.out.println("Now x2 is"+x2);
System.out.println("Now y2 is"+y2);
closed[x2][y2]=1;
}
}
}
}
}
return goal;
}
}
这是机器人运动的寻路算法,其中机器人声明位置为 (0,0),位置为 (4,5)。
每个单元格的成本是 1。我在这里使用网格矩阵创建了一个网格。其中 1 是障碍单元格。它有7个障碍物,即(0,1),(1,2),(2,4),(3,2)(3,3),(3,4)和(4,4)位置。我有一个封闭矩阵,它与网格矩阵具有相同的列和行。当机器人移动并占据一个单元格时,它将标记为 1 作为单元格被占用。
通过手动计算,我的目标位置(4,5)单元格中的成本为 11
但每当我运行此程序时,它显示位置(4,5)中的成本为 5,这是不可能的。我调试了这段代码,并在 3 次迭代后看到它考虑了被阻塞的单元格并通过了这个。
我认为 open.sort(); 和 open.reverse(); 制造问题。