Knight's Shortest Path on Chessboard

后端 未结 16 1298
情深已故
情深已故 2020-11-30 16:42

I\'ve been practicing for an upcoming programming competition and I have stumbled across a question that I am just completely bewildered at. However, I feel as though it\'s

16条回答
  •  情歌与酒
    2020-11-30 17:19

    public class Horse {
    
        private int[][] board;
        private int[] xer = { 2, 1, -1, -2, -2, -1, 1, 2 };
        private int[] yer = { 1, 2, 2, 1, -1, -2, -2, -1 };
        private final static int A_BIG_NUMBER = 10000;
        private final static int UPPER_BOUND = 64;
    
    
        public Horse() {
            board =  new int[8][8];
        }
    
        private int solution(int x, int y, int destx, int desty, int move) {
    
            if(move == UPPER_BOUND) {
                /* lets put an upper bound to avoid stack overflow */
                return A_BIG_NUMBER;
            }
    
            if(x == 6 && y ==5) {
                board[6][5] = 1;
                return 1;
            }
            int min = A_BIG_NUMBER;
            for (int i = 0 ; i < xer.length; i++) {
                if (isMoveGood(x + xer[i], y + yer[i])) {
                    if(board[x + xer[i]][y + yer[i]] != 0) {
                        min = Integer.min(min, 1 + board[x +xer[i]] [y +yer[i]]);                   
                    } else {
                        min = Integer.min(min, 1 + solution(x + xer[i], y + yer[i], destx, desty, move + 1));   
                    }                   
                }
            }   
            board[x][y] = min;
            return min;
        }
    
    
        private boolean isMoveGood(int x, int y) {
            if (x >= 0 && x < board.length && y >= 0 && y < board.length)
                return true;
            return false;
        }
    
    
        public static void main(String[] args) {
    
            int destX = 6;
            int destY = 7;
            final Horse h = new Horse();
            System.out.println(h.solution(0, 0, destX, destY, 0));
        }
    }
    

提交回复
热议问题