用java写的马踏棋盘算法

本文介绍了如何使用Java编程实现马踏棋盘算法。在8×8的国际象棋棋盘上,马按照其特有的移动规则,从任意一个起点开始,确保每个方格仅被访问一次,遍历所有64个方格。文章提供了代码示例和最终的结果展示。

用java写的马踏棋盘算法

将马随机放在国际象棋的8×8棋盘Board[0~7][0~7]的某个方格中,马按走棋规则进行移动。要求每个方格只进入一次,走遍棋盘上全部64个方格。


代码


/*
马踏棋盘问题
思路:
用深度优先遍历+回溯法
1,初始化一个8*8的矩阵,元素都为1
2,设定马的起始位置(x,y),对走过的节点做标记
3,对起始位置的下个一位置的8种可能,做循环操作,若没有路可走(也就是一条路走到头,发现返回结果为false),则开始进行回溯
4,在循环到的节点重复步骤2,3(也就是循环中用递归)。

要找到可能的线路,而不是简单的遍历所有,不能用广度优先遍历
*/
class HorseOnChessboard{
    static int[][] matrix=new int[8][8];
    static int[][] flag=new int[8][8];
    public static void createMatrix(){

        for(int i=0;i<8;i++){
            for(int j=0;j<8;j++){
                matrix[i][j]=0;
                flag[i][j]=0;
            }
        }
    }

    static int[] step1={1,1,-1,-1,2,2,-2,-2};
    static int[] step2={2,-2,2,-2,1,-1,1,-1};
    public static boolean check(int x,int y){
        if(x>7||x<0||y>7||y<0||flag[x][y]==1)
            return false;
        return true;
    }
    public static boolean dfs(int x,int y,int step){
        flag[x][y]=1;
        matrix[x][y]=step;
        if(step==64){
            print();
            return true;
        }
        for(int i=0;i<8;i++){
            if(check(x+step1[i],y+step2[i])){
                step++;
                boolean result=dfs(x+step1[i],y+step2[i],step);//参数局部变量,并不对x做改变
                if(result==true)//一直走到最后,若满足条件输出,若不满足回溯
                    return true;
                //这里节点使用的是局部变量x+step1,因此节点不用回溯
                flag[x+step1[i]][y+step2[i]]=0;
                matrix[x+step1[i]][y+step2[i]]=0;
                step--;
            }
        }

        return false;
    }
    public static void print(){
        for(int i=0;i<8;i++){
            for(int j=0;j<8;j++){
                System.out.print(matrix[i][j]+" ");
            }
            System.out.println("");
        }
    }
    public static void main(String[] args) {
        createMatrix();
        boolean f=dfs(1, 7, 1);
        System.out.println(f);
    }
}

结果

57 52 45 38 47 50 35 64
44 39 56 51 36 63 48 1
53 58 37 46 49 2 31 34
40 43 60 55 32 29 62 3
59 54 41 28 61 4 33 30
42 27 16 19 22 11 8 5
17 20 25 14 9 6 23 12
26 15 18 21 24 13 10 7
true

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值