Possible moves of the knight in chess.

javalearning Published on 15 February 2020


Given a chess board of dimension m * n.

Find number of possible moves where knight can be moved on a chessboard from given position. If mat[i][j] = 1 then the block is filled by something else, otherwise empty. Assume that board consist of all pieces of same color, i.e., there are no blocks being attacked.


  1. Input : mat[][] = {{1, 0, 1, 0},
  2.           {0, 1, 1, 1},
  3.           {1, 1, 0, 1},
  4.           {0, 1, 1, 1}}
  5.     pos = (2, 2)
  6. Output : 4
  7. Knight can moved from (2, 2) to (0, 1), (0, 3), 
  8. (1, 0) ans (3, 0).


We can observe that knight on a chessboard moves either:

1. Two moves horizontal and one move vertical

2. Two moves vertical and one move horizontal


The idea is to store all possible moves of knight and then count number of valid moves. A move will be invalid if:

1. A block is already occupied by another piece.

2. Move is out of chessboard.


Program in Java


public class Main { 

public static final int n = 4; 

public static final int m = 4; 


static int findPossibleMoves(int mat[][], int p, int q) 

int X[] = { 2, 1, -1, -2, -2, -1, 1, 2 }; 

int Y[] = { 1, 2, 2, 1, -1, -2, -2, -1 }; 


int count = 0; 


for (int i = 0; i < 8; i++) { 


int x = p + X[i]; 

int y = q + Y[i]; 


if (x >= 0 && y >= 0 && x < n && y < m 

&& mat[x][y] == 0) 

count++; 


return count; 


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));