马踏棋盘属于算法里的经典问题,这里用递归的方式给出一种解法:
package test; /** * Created by saishangmingzhu on 2018/11/25. */ public class Mataqipan { /** * 马踏棋盘问题: 将马放入8×8棋盘中指定的某方格,马按规则进行移动。 要求每个方格只进入一次,走遍棋盘上全部64个方格。求出马的行走路线,并按求出的行走路线将数字 1,2,…,64依次填入一个8×8的方阵并输出。 */ //【1】定义×××8*8,左下角为(0,0) //【2】定义马,占一格,可以向八个方向运动(1,1)->(3,2)/(2,3) // 即(+2,+1)/(+1,+2)/(-1,+2)/(-2,+1)/(-2,-1)/(-1,-2)/(+1,-2)/(+2,-1) // 递归 //【3】定义点,点就是二维数组 private int[][] newPointList=new int[8][8]; public static void main(String[] arg){ Mataqipan m=new Mataqipan(); m.move(0,0,1); } public void move(int x,int y,int level){ if (level==64){ for (int i=7;i>=0;i--){ for (int j=0;j<=7;j++){ if (newPointList[i][j]<10) { System.out.print("0"+newPointList[i][j] + ","); } else { System.out.print(newPointList[i][j] + ","); } } System.out.println(); } System.out.println("over"); System.exit(0); } int x1=0; int y1=0; x1=x+2; y1=y+1; //遍历八个方向的点 again(level, x1, y1); x1=x+1; y1=y+2; again(level, x1, y1); x1=x-1; y1=y+2; again(level, x1, y1); x1=x-2; y1=y+1; again(level, x1, y1); x1=x-2; y1=y-1; again(level, x1, y1); x1=x-1; y1=y-2; again(level, x1, y1); x1=x+1; y1=y-2; again(level, x1, y1); x1=x+2; y1=y-1; again(level, x1, y1); newPointList[x][y]=0; } private void again(int level, int x1, int y1) { //判断点是否超出范围,是否已被踩过 //重复move if (x1>=0&&x1<8&&y1>=0&&y1<8&&newPointList[x1][y1]==0){ newPointList[x1][y1]=level; move(x1,y1,level+1); } } }