Possible moves of knight | CPP program to find number of possible moves of knight ; To calculate possible moves ; All possible moves of a knight ; Check if each possible move is valid or not ; Position of knight after move ; count valid moves ; Return number of possible moves ; Driver program to check findPossibleMoves ( )
#include <bits/stdc++.h> NEW_LINE #define n  4 NEW_LINE #define m  4 NEW_LINE using namespace std ; int findPossibleMoves ( int mat [ n ] [ m ] , int p , int q ) { int X [ 8 ] = { 2 , 1 , -1 , -2 , -2 , -1 , 1 , 2 } ; int Y [ 8 ] = { 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 ; } int main ( ) { int mat [ n ] [ m ] = { { 1 , 0 , 1 , 0 } , { 0 , 1 , 1 , 1 } , { 1 , 1 , 0 , 1 } , { 0 , 1 , 1 , 1 } } ; int p = 2 , q = 2 ; cout << findPossibleMoves ( mat , p , q ) ; return 0 ; }