JAVA优化版,数据结构第60讲,马踏棋盘算法
本帖最后由 霁云飞 于 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;
private boolean findStep(int x, int y, int count) {
if (x-2 >= 0 && y-1 >= 0 && chess == 0) {
if(goStep(x-2, y-1, count+1)) {
return true;
}
}
if (x-1 >= 0 && y-2 >= 0 && chess == 0) {
if(goStep(x-1, y-2, count+1)) {
return true;
}
}
if (x+1 < MAX_X && y-2 >= 0 && chess == 0) {
if(goStep(x+1, y-2, count+1)) {
return true;
}
}
if (x+2 < MAX_X && y-1 >= 0 && chess == 0) {
if(goStep(x+2, y-1, count+1)) {
return true;
}
}
if (x+2 < MAX_X && y+1 < MAX_Y && chess == 0) {
if(goStep(x+2, y+1, count+1)) {
return true;
}
}
if (x+1 < MAX_X && y+2 < MAX_Y && chess == 0) {
if(goStep(x+1, y+2, count+1)) {
return true;
}
}
if (x-1 >= 0 && y+2 < MAX_Y && chess == 0) {
if(goStep(x-1, y+2, count+1)) {
return true;
}
}
if (x-2 >= 0 && y+1 < MAX_Y && chess == 0) {
if(goStep(x-2, y+1, count+1)) {
return true;
}
}
chess = 0;
return false;
}
public boolean goStep(int x, int y, int count) {
chess = 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
1129 52 25 42 59 56
167 28 23 38 61 50 45
3 12 17 62 51 32 37 60
18 156 29 22 35 46 49
134 63 20 33 48 31 36
64 19 145 30 21 34 47
页:
[1]