马踏棋盘

来源:互联网 发布:吉首大学官网网络 编辑:程序博客网 时间:2024/04/30 20:41
/*
 * 马踏国际象棋棋盘
 */
package test1;
import java.util.Scanner;


class Coordinate
{
int x;
int y;
public Coordinate(int a,int b)
{
x=a;
y=b;
}
}
public class demo {
static int[][] chessboard=new int[8][8];
static int curstep;
static Coordinate[] fangxiang={
new Coordinate(-2,1),
new Coordinate(-1,2),
new Coordinate(1,2),
new Coordinate(2,1),
new Coordinate(2,-1),
new Coordinate(1,-2),
new Coordinate(-1,-2),
new Coordinate(-2,-1)
};
static void Move(Coordinate curpos)
{
Coordinate next = new Coordinate(0,0);
int i,j;
if(curpos.x<0 || curpos.x>7 || curpos.y<0 || curpos.y>7)
return;
if(chessboard[curpos.x][curpos.y]!=0)
return;
chessboard[curpos.x][curpos.y]=curstep;
curstep++;
if(curstep > 64)
{
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
System.out.printf("%5d",chessboard[i][j]);

}
System.out.println();
}
System.exit(0);
}
else
{
for(i=0;i<8;i++)
{
next.x=curpos.x + fangxiang[i].x;
next.y=curpos.y + fangxiang[i].y;
if(next.x < 0 || next.x > 7 || next.y < 0 || next.y >7)
{

}
else
{
Move(next);

}
}
}
chessboard[curpos.x][curpos.y]=0;
curstep--;
}
public static void main(String[] args)
{
int i,j;
Coordinate start=new Coordinate(0,0);
for(i=0;i<8;i++)
{
for(j=0;j<8;j++)
{
chessboard[i][j]=0;
}
}
System.out.println("马踏棋盘问题求解!");
System.out.print("请输入马的一个初始位置(x,y):");
Scanner input = new Scanner(System.in);
start.x=input.nextInt();
start.y=input.nextInt();
if(start.x<1 || start.y<1 || start.x>8 || start.y>8)
{
System.out.println("初始位置输入错误,请重新输入!");
System.out.println("结束!");
}
start.x--;
start.y--;
curstep = 1;
Move(start);
}
}
0 0
原创粉丝点击