|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 霁云飞 于 2016-1-25 09:57 编辑
最近在听小甲鱼的数据结构,受益良多啊~就是听到第60讲的时候,把我听晕了,所以干脆自己写了个,感觉逻辑更清晰些,放上来供大家参考~
public class Horse {
private final int MAX_X = 8;
private final int MAX_Y = 8;
private int chess[][] = new int[MAX_X][MAX_Y];
private boolean findStep(int x, int y, int count) {
if (x-2 >= 0 && y-1 >= 0 && chess[x-2][y-1] == 0) {
if(goStep(x-2, y-1, count+1)) {
return true;
}
}
if (x-1 >= 0 && y-2 >= 0 && chess[x-1][y-2] == 0) {
if(goStep(x-1, y-2, count+1)) {
return true;
}
}
if (x+1 < MAX_X && y-2 >= 0 && chess[x+1][y-2] == 0) {
if(goStep(x+1, y-2, count+1)) {
return true;
}
}
if (x+2 < MAX_X && y-1 >= 0 && chess[x+2][y-1] == 0) {
if(goStep(x+2, y-1, count+1)) {
return true;
}
}
if (x+2 < MAX_X && y+1 < MAX_Y && chess[x+2][y+1] == 0) {
if(goStep(x+2, y+1, count+1)) {
return true;
}
}
if (x+1 < MAX_X && y+2 < MAX_Y && chess[x+1][y+2] == 0) {
if(goStep(x+1, y+2, count+1)) {
return true;
}
}
if (x-1 >= 0 && y+2 < MAX_Y && chess[x-1][y+2] == 0) {
if(goStep(x-1, y+2, count+1)) {
return true;
}
}
if (x-2 >= 0 && y+1 < MAX_Y && chess[x-2][y+1] == 0) {
if(goStep(x-2, y+1, count+1)) {
return true;
}
}
chess[x][y] = 0;
return false;
}
public boolean goStep(int x, int y, int count) {
chess[x][y] = count;
if (count == MAX_X * MAX_Y) {
for (int i[] : chess) {
for (int j : i) {
System.out.printf("%3d", j);
}
System.out.println();
}
return true;
}
return findStep(x, y, count);
}
public static void main(String[] args) {
Horse horse = new Horse();
horse.goStep(0, 0, 1);
}
}
运行结果:
1 10 53 26 43 40 55 58
8 27 24 39 54 57 44 41
11 2 9 52 25 42 59 56
16 7 28 23 38 61 50 45
3 12 17 62 51 32 37 60
18 15 6 29 22 35 46 49
13 4 63 20 33 48 31 36
64 19 14 5 30 21 34 47
|
|