用java写的马踏棋盘算法

来源:互联网 发布:mac os x壁纸 编辑:程序博客网 时间:2024/05/03 18:59

用java写的马踏棋盘算法

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


代码

/*马踏棋盘问题思路:用深度优先遍历+回溯法1,初始化一个8*8的矩阵,元素都为12,设定马的起始位置(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

0 0