日期:2014-05-20 浏览次数:21228 次
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
public class Test3 {
List<Point> list = new ArrayList<Point>();
public static void main(String[] args) {
Test3 test = new Test3();
test.list.add(new Point(0, 0));
test.path(new Point(0, 0));
}
public void path(Point curPoint) {
if (curPoint.x > 8 || curPoint.y > 4 || curPoint.x < 0
|| curPoint.y < 0)
return;
if (curPoint.x == 8) {
for (int i = 0; i < list.size(); i++) {
System.out.print("(" + list.get(i).x + "," + list.get(i).y
+ ")");
}
System.out.println();
return;
}
Point point = new Point(curPoint.x + 1, curPoint.y + 2);
fun(point);
point = new Point(curPoint.x + 2, curPoint.y + 1);
fun(point);
// point = new Point(curPoint.x - 1, curPoint.y + 2);
// fun(point);
//
// point = new Point(curPoint.x - 2, curPoint.y + 1);
// fun(point);
point = new Point(curPoint.x + 1, curPoint.y - 2);
fun(point);
point = new Point(curPoint.x + 2, curPoint.y - 1);
fun(point);
// point = new Point(curPoint.x - 1, curPoint.y - 2);
// fun(point);
//
// point = new Point(curPoint.x - 2, curPoint.y - 1);
// fun(point);
}
private void fun(Point point) {
if (!list.contains(point)) {
list.add(point);
path(point);
list.remove(point);
}
}
}
------解决方案--------------------
public class HorseMove {
static Boolean isAllow(int x, int y){
if(x >= 0 && x <= 8 && y >= 0 && y <= 4)
return true;
return false;
}
static void move(int x, int y, int[][] mean, int[][] step, int stepCnt){
if(x == 8 && y >= 0 && y <= 4){
System.out.print("(0 0) ");
for(int i = 0; i < 8 && step[0][i]!=0; ++i)
System.out.print("(" + step[0][i] + " " + step[1][i] + ") ");
System.out.println();
return;
}
for(int j = 0; j < 4; ++j){
if(isAllow(x+mean[0][j], y+mean[1][j])){
step[0][stepCnt] = x+mean[0][j];
step[1][stepCnt] = y+mean[1][j];
move(x+mean[0][j], y+mean[1][j], mean, step, stepCnt+1);
}
}
}
public static void main(String[] args){
int[][] mean = {{1, 2, 2, 1}, {2, 1, -1, 2}};
int[][] step = new int[2][8];
for(int i = 0; i < 2; ++i)
for(int j = 0; j < 8; ++j)
step[i][j] = 0;
move(0, 0, mean, step, 0);
}
}
------解决方案--------------------