骑士周游列国问题(马踏棋盘算法)

思路: 就是递归。先扫描所有可以走的点,然后利用遍历和递归。发现计算器等于格子数时完成。
优化: 遍历和递归的基础上再加贪心算法,第 i 步的位置按照 i+1 步可以落子位置的数量进行升序排列(优先遍历 i+1 步位置少的,以便减少遍历次数)
我这里没有优化,优化就是把我第二个方法再封装一个方法,稍微改动即可。


import java.util.ArrayList;

/**
 * @author 王木风
 * @create 2020-08-30 12:19
 */
public class HorseChessboard {
    //计数器
    static int step = 1;
    public static void main(String[] args) {
        int[][] checkerBoard = new int[8][8];
        coreMethod(checkerBoard,0,0);
        //验证
        for (int[] ints :checkerBoard) {
            for (int i :ints) {
                System.out.print(i+"\t");
            }
            System.out.println();
        }
        System.out.println(step);
    }

    public static void coreMethod(int[][] checkerBoard,int i,int j) {
        //记录该点是第几步
        checkerBoard[i][j] = step;
        //存放下一步落子位置的x,y
        ArrayList<int[]> ints = new ArrayList<>();
        if (i + 2 < 8 && j + 1 < 8 && checkerBoard[i+2][j+1] == 0) {
            ints.add(new int[]{i+2,j+1});
        }
        if (i + 1 < 8 && j + 2 < 8 && checkerBoard[i+1][j+2] == 0) {
            ints.add(new int[]{i+1,j+2});
        }
        if (i - 1 < 8 && j + 2 < 8 && i - 1 >= 0 && checkerBoard[i - 1][j + 2] == 0 ) {
            ints.add(new int[]{i - 1, j + 2});
        }
        if (i - 2 < 8 && j + 1 < 8 && i - 2 >= 0 && checkerBoard[i - 2][j + 1] == 0) {
            ints.add(new int[]{i - 2, j + 1});
        }
        if (i - 2 < 8 && j - 1 < 8 && i - 2 >= 0 && j - 1 >= 0 && checkerBoard[i - 2][j - 1] == 0) {
            ints.add(new int[]{i - 2, j - 1});
        }
        if (i - 1 < 8 && j - 2 < 8 && i - 1 >= 0 && j - 2 >= 0 && checkerBoard[i - 1][j - 2] == 0) {
            ints.add(new int[]{i - 1, j - 2});
        }
        if (i + 1 < 8 && j - 2 < 8 && j - 2 >= 0 && checkerBoard[i + 1][j - 2] == 0) {
            ints.add(new int[]{i + 1, j - 2});
        }
        if (i + 2 < 8 && j - 1 < 8 && j - 1 >= 0 && checkerBoard[i + 2][j - 1] == 0) {
            ints.add(new int[]{i + 2, j - 1});
        }
        //遍历可以落子位置
        for (int[] arr :ints) {
            if (step < 64) {
                step++;
                //递归
                coreMethod(checkerBoard, arr[0], arr[1]);
            }
        }
        if (step == 64) {
            return;
        } else {
            //如果无位置可落,则计数器退1.该点置零
            step--;
            checkerBoard[i][j] = 0;
        }
    }
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值