我是一名优秀的Java程序员,将A *算法实现为java代码,但是它没有产生预期的结果
具体来说我有类Grid
public class Grid implements Comparable<Grid> {
int depth=0;
public Tile [] [] puzzle= new Tile [SlidePuzzleModel.ROWS] [SlidePuzzleModel.COLS];
public static String [] [] goal= { {"","1","2","3"},{"4","5","6","7"},{"8","9","10","11"}, {"12","13","14","15"}};
private int unobserved;
private int cost;
我的CompareTo方法如下:
public int compareTo(Grid arg0) {
Grid other = (Grid) (arg0);
if (this.cost >= other.cost) {
return 1;
} else if (this.cost < other.cost) {
return -1;
}
return 0;
}
我的equlas如下:
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Grid other = (Grid) obj;
if (!Arrays.deepEquals(this.puzzle, other.puzzle)) {
return false;
}
if (this.depth != other.depth) {
return false;
}
return true;
}
我的哈希码功能如下:
@Override
public int hashCode() {
int hash = 5;
hash = 67 * hash + Arrays.deepHashCode(this.grid);
return hash;
}*/
问题在于,在我的A *方法中,我创建了类型为ArrayList()的闭合列表,并且我使用了方法.contains但是我不知道为什么它总是返回true。 这是我的主张声明
public boolean Astar(Grid initialState)
{
PriorityQueue<Grid> fringe = new PriorityQueue<Grid>();
List<Grid> closed = new ArrayList<Grid>();
List<Grid> MyList;
boolean found=false;
fringe.add(initialState);
boolean contain;
int count=0;
while(fringe.isEmpty()==false && !found)// && !failure)
{
count++;
System.out.println(" i is " +count);
//get state from fringe
Grid current = fringe.poll();
if(current.WaW(current))
{
System.out.println("I am inside current.waw==true");
found=true;
break;
}
else
{
System.out.println("I am inside ELSE current.waw==true");
contain=closed.contains(current);
if (contain==false)
{
System.out.println("I am inside contain==false");
numOfNodeGenerated++;
Grid nextState = current;
//pos of empty tile
int [] emptyPos=checkEmpty(nextState);
MyList= moveTile (emptyPos[0], emptyPos[1]);
System.out.println(";MyList.size() is "+ MyList.size());
for (int i=0; i< MyList.size(); i++)
{
System.out.println("I am inside My List Loop");
Grid gr=MyList.remove(i);
int hn=manhatten(gr);
int gn=numOfNodeGenerated-1;
gr.setCost(hn+gn);
fringe.add(gr);
}
}
closed.add(current);
}//END if
//after expanding add it to closed
}//end while
System.out.println("I am out of the loop");
return found;
}
我得到的输出是: 运行:
4
i is 1
I am inside ELSE current.waw==true
I am inside contain==false
4
;MyList.size() is 4
I am inside My List Loop
I am inside My List Loop
i is 2
I am inside ELSE current.waw==true
i is 3
I am inside ELSE current.waw==true
I am out of the loop