在矩阵中从源移动到目的地的最小骑士移动次数

时间:2016-11-23 07:41:01

标签: java algorithm dynamic-programming depth-first-search breadth-first-search

我的目标是使用矩阵中最短的步数从source移动到destination,只做骑士移动(L形移动)

深度优先搜索解决方案是否适用于此案例?我对处理已访问过的节点的方式感到担心。如果这是一个有效的解决方案,请告诉我。

public class knightminmoves {

    /**
     * @param args
     */
    public static void main( String[] args ) {
        // TODO Auto-generated method stub

        int degree = 5;
        int[][] board = new int[degree][degree];
        boolean[][] visited = new boolean[degree][degree];

        System.out.println( minMoves( 0, 0, degree - 1, degree - 1, board, visited ) );
    }


    static int minMoves( int x, int y, int destx, int desty, int[][] board, boolean[][] visited ) {
        if ( x < 0 || y < 0 || x >= board.length || y >= board[0].length )
            return Integer.MAX_VALUE - 2;

        if ( x == destx && y == desty )
            return 0;

        if ( visited[x][y] == true )
            return Integer.MAX_VALUE - 2;
        else
            visited[x][y] = true;

        int upleft = minMoves( x - 2, y - 1, destx, desty, board, visited );
        int upright = minMoves( x - 2, y + 1, destx, desty, board, visited );
        int downleft = minMoves( x + 2, y - 1, destx, desty, board, visited );
        int downright = minMoves( x + 2, y + 1, destx, desty, board, visited );
        int leftup = minMoves( x - 1, y - 2, destx, desty, board, visited );
        int leftdown = minMoves( x + 1, y - 2, destx, desty, board, visited );
        int rightup = minMoves( x - 1, y + 2, destx, desty, board, visited );
        int rightdown = minMoves( x + 1, y + 2, destx, desty, board, visited );

        visited[x][y] = false;

        return min( upleft, upright, downleft, downright, leftup, leftdown, rightup, rightdown ) + 1;
    }

    static int min( int a, int b, int c, int d, int e, int f, int g, int h ) {
        int[] arr = new int[8];
        arr[0] = a;
        arr[1] = b;
        arr[2] = c;
        arr[3] = d;
        arr[4] = e;
        arr[5] = f;
        arr[6] = g;
        arr[7] = h;

        Arrays.sort( arr );
        return arr[0];
    }

}

1 个答案:

答案 0 :(得分:1)

您的代码是正确的,但速度很慢。它不是深度优先搜索。因为它将访问节点标记为未访问的节点,所以您的程序只生成所有简单路径并选择最短路径。这是一次详尽的搜索。它具有指数时间复杂度,因此在较大的电路板上完成需要很长时间。您可以使用广度优先搜索来获得可以很好地扩展的有效且正确的解决方案。