内容转载自程序实现部分
package Picture;
import java.awt.Point;
import java.util.ArrayList;
import java.util.Scanner;
public class QiShi {
private static int X=8;//棋盘的行数
private static int Y=8;//棋盘的列数
private static boolean visited[];
private static boolean finished=false;
//在当前位置处,搜寻下一步的可能位置,并放入list中
public static ArrayList<Point> Next(Point p) {
ArrayList<Point>resultArrayList=new ArrayList<Point>();
Point p1=new Point();
if ((p1.x = p.x - 2) >= 0 && (p1.y = p.y - 1) >= 0) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x - 1) >= 0 && (p1.y = p.y - 2) >= 0) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x + 1) < X && (p1.y = p.y - 2) >= 0) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x + 2) < X && (p1.y = p.y - 1) >= 0) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x + 2) < X && (p1.y = p.y + 1) < Y) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x + 1) < X && (p1.y = p.y + 2) < Y) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x - 1) >= 0 && (p1.y = p.y + 2) < Y) {
resultArrayList.add(new Point(p1));
}
if ((p1.x = p.x - 2) >= 0 && (p1.y = p.y + 1) < Y) {
resultArrayList.add(new Point(p1));
}
return resultArrayList;
}
//遍历棋盘
public static void Travel(int [][]chessBoard,int row,int comlun,int step) {
chessBoard[row][comlun]=step;
visited[row*Y+comlun]=true;
ArrayList<Point> nextPoints=Next(new Point(row,comlun));
while (!nextPoints.isEmpty()) {
Point point=nextPoints.remove(0);
if(!visited[point.x*Y+point.y])
{
Travel(chessBoard, point.x, point.y, step+1);
}
}
if(step<X*Y && !finished)
{
chessBoard[row][comlun]=0;
visited[row*Y+comlun]=false;
}
else {
finished=true;
}
}
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("请输入棋盘的行数和列数");
do {
X=sc.nextInt();
Y=sc.nextInt();
} while (X<=0||Y<=0);
System.out.println("请输入起始位置(先行后列)");
int row,column;
do {
row=sc.nextInt();
column=sc.nextInt();
} while (row<=0||row>X||column<=0||column>Y);
int [][] chessBoard=new int[X][Y];
visited=new boolean[X*Y];
long starttime=System.currentTimeMillis();
Travel(chessBoard, row-1, column-1,1);
long endtime=System.currentTimeMillis();
System.out.println("共耗时:"+(endtime-starttime)+"ms");
for(int []rows:chessBoard)
{
for(int columns:rows)
{
System.out.print(columns+"\t");
}
System.out.println();
}
sc.close();
}
}