马走日算法

 回溯法
 1.定义:类似于枚举的搜索尝试过程,主要是在搜索尝试中寻找问题的解,当发现不满足求解条件时,
	就回溯返回,尝试其他的路径。
 2.基本思想:图的深度优先遍历,即从根节点出发遍历解空间,当遍历到某一结点时,先判断该节点是否
		包含问题的解,若包含,则沿着该结点继续进行深度优先遍历,如果不包含,则回退一步。
 3.回溯法解决问题的步骤
   (1)针对所给的问题,确定解空间:首先明确问题的解空间,问题的解空间至少包含问题的一个(最优)解。
  (2)确定结点的搜索规则
  (3)以深度优先方式搜索解空间,并在搜索过程中采用剪枝函数避免无效搜索

public class exercise3 {
    //定义马走日的下一位置相对于当前位置的坐标
    private static int [][]next=new int[][]{{1,2},{1,-2},{-1,2},{-1,-2},{2,1},{2,-1},{-2,1},{-2,-1}};
    private static int [][]book;//走过的位置的标记
    private static int [][]map;//棋盘的大小
    private static int [][]a;//路径信息标号
    private static int n,m;
    private static int count=0;//记录多少种走法

    public static void main(String[] args) {
        n=5;
        m=5;//棋盘为5*5
        int x=0,y=0;//定义初始位置
        map=new int[n][m];
        book=new int[n][m];
        a=new int[n][m];
        book[x][y]=1;//标记为起点已访问
        dfs(x, y,1);
        System.out.printf("总共可能的情况:%3d",count);
    }

    private static void dfs(int x, int y,int step) {
        a[x][y]=step;
        if(step==n*m){
            if(count==0)
                print(a);//输出一种情况,可以注释if,输出所有情况
            count++;
        }
        int tx=0,ty=0;
        for(int i=0;i<8;i++){
            tx=x+next[i][0];
            ty=y+next[i][1];
            //判断是否出界
            if(tx<0||tx>=n||ty<0||ty>=m)
                continue;
            if(book[tx][ty]==0){
                book[tx][ty]=1;
                dfs(tx,ty,step+1);
                book[tx][ty]=0;
            }
        }
    }

    private static void print(int [][]arr) {
        for(int i=0;i<n;i++){
            for(int j=0;j<m;j++)
                System.out.print(arr[i][j]+"\t");
            System.out.println();
        }
        System.out.println("----------");
    }
}

猜你喜欢

转载自blog.csdn.net/sir_ti/article/details/80333073