Knight's tour

You are given a chess-board and a starting point co-oridnates. You are given a knight, which starts at the starting point. You've to check whether the knight can visit all the spots in the chess-board.

Input Format:

N (integer) - size of 2-d array

X (integer) - x-coordinate of starting point

Y (integer) - y-coordinate of starting point Constraints

0 <= N <= 5

0 <= X < N

0 <= Y < N

Output Format: true or false

Sample Input: 5 0 0

Sample Output: true

class Solution {
    static int moves[][] = { { 1, 2 }, { -1, 2 }, { 1, -2 }, { -1, -2 }, { 2, 1 }, { 2, -1 }, { -2, 1 }, { -2, -1 } };

    public static int DFS(int n, int x, int y, boolean[][] visited) {
        if (x < n && x >= 0 && y < n && y >= 0 && !visited[x][y]) {
            int ans = 1;
            visited[x][y] = true;
            for (int[] move : moves) {
                int smallAns = DFS(n, x + move[0], y + move[1], visited);
                if (smallAns != -1)
                    ans = Math.max(ans, smallAns + 1);
            }
            visited[x][y] = false;
            return ans;
        }
        return -1;
    }

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        int n = s.nextInt(), x = s.nextInt(), y = s.nextInt();
        boolean[][] visited = new boolean[n][n];
        int result = DFS(n, x, y, visited);
        System.out.println(result == n * n);
    }
}

Last updated