Possible moves of a knight.Given a chessboard of dimension m * n. Find a number of possible moves where the knight can be moved on a chessboard from a given position. If mat[i][j] = 1 then the block is filled by something else, otherwise empty. Assume that the board consist of all pieces of the same color, i.e., there are no blocks being attacked. Input : mat[][] = {{1, 0, 1, 0}, {0, 1, 1, 1}, {1, 1, 0, 1}, {0, 1, 1, 1}} pos = (2, 2) Output : 4 Knight can moved from (2, 2) to (0, 1), (0, 3), (1, 0) ans (3, 0). // Java program to find number of possible moves of knight public class Main { public static final int n = 4; public static final int m = 4; // To calculate possible moves static int findPossibleMoves(int mat[][], int p, int q) { // All possible moves of a knight int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; int count = 0; // Check if each possible move is valid or not for (int i = 0; i < 8; i ) { // Position of knight after move int x = p X[i]; int y = q Y[i]; // count valid moves if (x >= 0 && y >= 0 && x < n && y < m && mat[x][y] == 0) count ; } // Return number of possible moves return count; } // Driver program to check findPossibleMoves() public static void main(String[] args) { int mat[][] = { { 1, 0, 1, 0 }, { 0, 1, 1, 1 }, { 1, 1, 0, 1 }, { 0, 1, 1, 1 } }; int p = 2, q = 2; System.out.println(findPossibleMoves(mat, p, q)); } } - Study24x7
Social learning Network
study24x7

Default error msg

Login

New to Study24x7 ? Join Now
Already have an account? Login
86 followers study24x7 15 Nov 2019 06:10 PM study24x7 study24x7

Possible moves of a knight.Given a chessboard of dimension m * n. Find a number of possible moves where the knight can be moved on a chessboard from a given position. If mat[i][j] = 1 then the block is filled by something else, otherwise empty. Assume that the board consist of al...

See more

study24x7
Write a comment
Most Related Articles