尝试了很多方法目前只有这一种能成功。。。
package algorithm;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
public class TravelChessBoard {
int[][] chess;
int len;
boolean isFinished;
boolean[][] isVisited;
public TravelChessBoard(int[][] chess) {
this.chess = chess;
this.len = chess.length;
isFinished = false;
isVisited = new boolean[len][len];
for(int i=0; i<len; i++) {
for(int j=0; j< len; j++) {
isVisited[i][j] = false;
}
}
}
public ArrayList<Point> next(int x, int y){
ArrayList<Point> next = new ArrayList<Point>();
if((x-2) >= 0 && (y+1) < len ) {
next.add(new Point(x-2 , y+1));
}
if((x-1) >= 0 && (y+2) < len) {
next.add(new Point(x-1 , y+2));
}
if((x+1) < len && (y+2) < len) {
next.add(new Point(x+1 , y+2));
}
if((x+2) <len && (y+1) < len ) {
next.add(new Point(x+2 , y+1));
}
if((x+2) < len && (y-1) >= 0 ) {
next.add(new Point(x+2 , y-1));
}
if((x+1) < len && (y-2) >= 0) {
next.add(new Point(x+1, y-2));
}
if((x-1) >= 0 && (y-2) >= 0) {
next.add(new Point(x-1 , y-2));
}
if((x-2) >= 0 && (y-1) >= 0) {
next.add(new Point(x-2 , y-1));
}
return next;
}
public void sort(ArrayList<Point> ps) {
ps.sort(new Comparator<Point>() {
@Override
public int compare(Point o1, Point o2) {
// TODO Auto-generated method stub
return next(o1.x,o1.y).size() - next(o2.x,o2.y).size();
}
});
}
public void travel(int[][] chess, int x, int y,int count) {
System.out.println(count);
chess[x][y] = count;
isVisited[x][y] = true;
ArrayList<Point> ps = next(x,y);
// sort(ps);
while(!ps.isEmpty()) {
Point p = ps.remove(0);
if(!isVisited[p.x][p.y]) {
travel(chess, p.x,p.y, count+1);
}
}
//如果count>=len*len,说明已经找到解
if(count>=len*len) {
isFinished = true;
}
//走到这里说明已经走完上面所有可能路径,如果没有找到解,将chess[x][y]置零,并置为未访问。回溯上面其他路径。
if(!isFinished) {
chess[x][y] = 0;
isVisited[x][y] = false;
}
}
public void show(int[][] chess) {
for(int[] i : chess) {
System.out.println(Arrays.toString(i));
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] chess = new int[6][6];
TravelChessBoard tcb = new TravelChessBoard(chess);
long start = System.currentTimeMillis();
tcb.travel(chess, 0, 0, 1);
tcb.show(chess);
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}