马踏棋盘小游戏

先定义一个游戏类horseChessBoard

和一些属性

    private static int X = 6;//表示列
    private static int Y = 6;//表示行
    private static int[][] chessBoard = new int[Y][X];//二维数组表示棋盘
    private static boolean[] visited = new boolean[X * Y];//记录某个位置是否走过
    private static boolean finished = false;//记录棋子是否遍历完整个棋盘

这里定义一个6*6的棋盘

 我们接下来用一个算法来计算棋子下一步能走的位置,把他放入一个集合中

next方法

    //此方法可以获得当前位置可以走的下一步的所有位置
    public static ArrayList<Point> next(Point curPoint) {
        ArrayList<Point> ps = new ArrayList<>();//创建一个数组存放这些位置
        Point p = new Point();
        if ((p.x = curPoint.x - 2) >= 0 && (p.y = curPoint.y - 1) >= 0) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x - 1) >= 0 && (p.y = curPoint.y - 2) >= 0) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x + 1) < X && (p.y = curPoint.y - 2) >= 0) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x + 2) < X && (p.y = curPoint.y - 1) >= 0) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x + 2) < X && (p.y = curPoint.y + 1) < Y) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x + 1) < X && (p.y = curPoint.y + 2) < Y) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x - 1) >= 0 && (p.y = curPoint.y + 2) < Y) {
            ps.add(new Point(p));
        }
        if ((p.x = curPoint.x - 2) >= 0 && (p.y = curPoint.y + 1) < Y) {
            ps.add(new Point(p));
        }
        return ps;
    }

这里函数返回值为一个ArrayList泛型数组,存放的是Point类

这里用Point对象来表示坐标

这8个if是判断棋子当前坐标能否到下一个坐标,如果能,创建一个新的Point对象加入数组中,这个新的对象的坐标是判断成功的值

现在我们开始整个程序最重要的部分,算法实现

traversal方法

//遍历棋盘
    public static void  traversal(int[][] chessBoard,int row,int col,int step){
        chessBoard[row][col] = step;
        visited[row*X+col]=true;
        ArrayList<Point> ps= next(new Point(col,row));
        while (!ps.isEmpty()){
            Point p=ps.remove(0);
            if(!visited[p.y*X+p.x]){
                traversal(chessBoard,p.y,p.x,step+1);
            }
        }
        if(step<X*Y && !finished){
            chessBoard[row][col]=0;
            visited[row*X+col]=false;
        }else {
            finished=true;
        }
    }

调用此函数需要几个参数,棋盘,行和列坐标,第几步

我们先将该坐标设置为第几步,然后设置visited为true(已被访问)

利用行列坐标创建一个Point对象,调用next方法

把方法返回值赋给一个数组

现在开始循环,只要数组不为空,就取出一个Point对象(remove方法是根据标号删除数组对应元素,然后返回值为要删除的元素)判断是否已访问,如果没有,递归调用traversal进入下一步

下面的if判断是当步数小于棋盘大小(没有走过所有点)或者finished(没有完成),就设置该点为零,表示此路不通,如果不是那说明找到路了

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值