package com.bjtutz.fiveballgame;import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import android.graphics.Point;public class PathArithmetic {
private ArrayList<Bead> path;
private ArrayList<Bead> invalidate;

private static PathArithmetic pathArithmetic = new PathArithmetic();
private PathArithmetic(){}
/** 单例模式 */
public static PathArithmetic getInstance(){
return pathArithmetic;
}
public ArrayList<Bead> getPath(int[][] chess, Bead from, Bead to) {
invalidate = new ArrayList<Bead>();
path = new ArrayList<Bead>();
boolean flag = isLink(chess , from , to);
//System.out.println(flag);
//System.out.println(path);
return path;
}

private boolean isLink(int[][] chess,Bead from, final Bead to) {
//第一步:记录经过的点
invalidate.add(from);
//第二步:获取上、下、左、右四个点
Bead[] beads = {
new Bead(from.x , from.y - 1),
new Bead(from.x , from.y + 1),
new Bead(from.x - 1 , from.y),
new Bead(from.x + 1 , from.y)
};
//第三步:判断四个点是否有效或者是目的点
List<Bead> lists = new ArrayList<Bead>();
for(Bead bead : beads){
if(bead.equals(to)){
path.add(to);
return true;
}
if(check(chess,bead)){
lists.add(bead);
}
}
//第四步:判断有效点是否全部被占完
if(lists.isEmpty()) return false;
//第五步:对有效点进行按最短路径排序
Collections.sort(lists, new Comparator<Bead>() {
//对lists集合按照compare方法进行比较
public int compare(Bead lhs, Bead rhs) {
//x*x + y*y开平方根
double r1 = Math.sqrt((lhs.x - to.x)*(lhs.x - to.x) + (lhs.y - to.y)*(lhs.y - to.y));
//System.out.println("r1:" + r1);
double r2 = Math.sqrt((rhs.x - to.x)*(rhs.x - to.x) + (rhs.y - to.y)*(rhs.y - to.y));
//System.out.println("r2:" + r2);
if(r1 < r2) return -1;
return 0;
}
});
//第六步:递归找出有效点及到搜索到目的点或有效点全部搜索完毕
for(Bead p : lists){
boolean flag = isLink(chess,p ,to);
if(flag){
path.add(p);
return true;
}
}
return false;
}




private boolean check(int[][] chess,Bead bead) {
if(invalidate.contains(bead)){
//搜索过的点不需要再搜索
return false;
}
return bead.x >= 0 && bead.x < chess.length
&& bead.y >= 0 && bead.y < chess.length
&& chess[bead.x][bead.y] == 0;
}}
我在做一个安卓的游戏,这部分功能是一个棋盘里一个棋子从一个格移动到另一个格的算法
里面bead是相当于point,chess是棋盘数组,为0代表没有棋子可以移动到那里。
感觉没什么问题,结果一运行就报错,提示stackoverflowerror,貌似递归有问题,求大神解答算法path棋盘