Possible moves of knight in C++


In this problem, we are given an m*n chessboard with filled positions marked by 1 i.e. if board[i][j] = 1, there is some piece there and we are given the starting position. Our task is to find the total number of possible moves for a knight in the board, if there are all pieces of the same color i.e. no attack will be done.

Knight is chess is a piece that can move in all directions with some special sort of move. The moves of Knight in chess are −

  • Two horizontal moves and a vertical move.

  • Two vertical moves and a horizontal move.

Let’s take an example to understand the problem,

Input

board[][] = {
   { 0, 1, 0, 0 },
   { 0, 0, 1, 1 },
   { 0, 1, 1, 0 },
   { 0, 0, 0, 1 }
};
Position : (1,1)

Output − 4

To solve this problem, we need to find what are the valid moves out of all possible moves of a knight in the chessboard. A move is valid if it moves off a position that is in the chessboard and is not pre-occupied by any other piece.

For this, we will store all possible moves of the knight from the given position. And then check for the validity of each move and increase the count for each valid move.

Example

Program to show the implementation of our solution −

 Live Demo

#include <bits/stdc++.h>
#define N 8
#define M 8
using namespace std;
int countPossibleMoves(int mat[N][M], int p, int q){
   int Xmoves[8] = { 2, 1, -1, -2, -2, -1, 1, 2 };
   int Ymoves[8] = { 1, 2, 2, 1, -1, -2, -2, -1 };
   int count = 0;
   for (int i = 0; i < 8; i++) {
      int x = p + Xmoves[i];
      int y = q + Ymoves[i];
      if (x>=0 && y>=0 && x<N && y<M && mat[x][y]==0)
         count++;
   }
   return count;
}
int main(){
   int mat[N][M] = { { 0, 1, 0, 0 },
      { 0, 0, 1, 1 },
      { 0, 1, 1, 0 },
      { 0, 0, 0, 1 }};
   int position[2] = {1,1};
   cout<<"Total number of moves possible for Knight from position ("<<position[0]<<" , "<<position[1]<<") are : ";
   cout<<countPossibleMoves(mat, position[0], position[1]);
   return 0;
}

Output

Total number of moves possible for Knight from position (1 , 1) are : 4

Updated on: 17-Apr-2020

766 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements