马踏棋盘-----Java版

来源:互联网 发布:虚拟蓝牙适配器软件 编辑:程序博客网 时间:2024/05/21 06:38

关于马踏棋盘的思路,大致算法如下:
1.贪心算法(找最少的出路,因为最少的出路往往不用进行多次选择,贪 心算法的主要理念是:最拿走的路是最好的路);
2.深度搜索:主要的算法是深入进去探索,但执行时间有点长,效率有点低,但搜索面比较广泛;
3.回溯:当搜索到该点没有出路时,就退回到上一个点的位置;
4.递归:马踏棋盘主要用到是递归的方法,递归循环;

闲话不多说,来看看代码吧。。。。。

package ma;import java.util.Scanner;public class ma {    //马在一个点时,能走的方向有8个;    static final int[] fx = {-1,-2,-2,-1,1,2,2,1};    static final int[] fy={2,1,-1,-2,-2,-1,1,2};    static final int N =8;              //棋盘的大小;    static int[][] board = new int[N][N];//马走的棋盘;    class manode{        int x;          //x坐标        int y;          //y坐标        int way;        //该点有多少种走法;     }                   //定义一个内部类,马所在点的信息;    int wayout(int x,int y){        int tx,ty;        int count = 0;        if(x<0||y<0||x>=N||y>=N||board[x][y]>0){            return -1;        }               //当点超出边界或者所在的点的值不为0时,返回-1;        for(int i = 0;i<N;i++){            tx = x+fx[i];            ty = y+fy[i];            if(tx<0||ty<0||tx>=N||ty>=N){                continue;//如果点的另一个点超出边界时,就continue;            }            if(board[tx][ty] == 0){                count++;//否则计数器计数;            }        }        return count;    }//计算该点的走法有多少种;    void sort(manode[] hn,int n){        int i,j,k;        manode temp;    //临时对象,用来排序交换;        for(i=0;i<n;i++){            for(k=i,j=i+1;j<n;j++){                if(hn[j].way<hn[k].way)                    k=j;            }            if(k>i){                temp = hn[i];                hn[i] = hn[k];                hn[k] = temp;            }        }    }//将走法的数量进行排序,将最少的走法放在数组的头;    void dfs(int x,int y,int count){        int i,tx,ty;        manode[] t = new manode[N];        if(count >N*N){            output();            return;        }   //当count计数器超过64时,打印输出;        for(i=0;i<N;i++){            tx = x+fx[i];            ty = y+fy[i];            manode h = new manode();            t[i]=h;            t[i].x = tx;            t[i].y = ty;            t[i].way = wayout(tx,ty);        }        sort(t,N);        for(i = 0;t[i].way<0;i++)            ;        for(;i<N;i++){            tx = t[i].x;            ty = t[i].y;            board[tx][ty] = count;            dfs(tx,ty,count+1);            board[tx][ty] = 0;//遇到死路时,回退回去,并将其变成0;        }    }//深度搜索与回溯算法;    public static void main(String[] args) {        int x,y;        Scanner input = new Scanner(System.in);        System.out.println("please input x,y:");        x = input.nextInt();        y = input.nextInt();        ma test = new ma();        board[x][y]=1;        test.dfs(x, y, 2);    }    void output(){        for(int i = N-1;i>=0;i--){            for(int j = 0;j<N;j++){                System.out.printf("%d\t",board[i][j]);            }            System.out.printf("\n\n\n");        }        System.exit(0);    }       //打印输出函数;}

that is all…end…..thank you….

0 0