Skip to content

Instantly share code, notes, and snippets.

@McLarenCollege
Last active October 6, 2022 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save McLarenCollege/d08fa5230c1212676afe47ceb1bade07 to your computer and use it in GitHub Desktop.
Save McLarenCollege/d08fa5230c1212676afe47ceb1bade07 to your computer and use it in GitHub Desktop.
Possible Knight Moves

Time Allowed : 45 minutes

Given a square chessboard and a knight occupying a cell return the number of the possible positions it can take after making a move.

The letter 'K' denotes the current knight position.

For eg.

chessBoard=[[' ',' ',' ',' '],
            [' ',' ',' ',' '],
            [' ','K',' ',' '],
            [' ',' ',' ',' ']];
chessBoard2=[[' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' '],
             [' ','K',' ',' ',' '],
             [' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' ']];
chessBoard3=[['K',' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' ',' '],
             [' ',' ',' ',' ',' ',' ']];
 function possibleKnightMoves(chessBoard){
 //write your code here
 }
 console.log(possibleKnightMoves(chessBoard));//returns 4 becuase possible moves are[[0,0],[0,2],[1,3],[3,3]];
 console.log(possibleKnightMoves(chessBoard2));// returns 6 because possible moves are[[0,0],[0,2],[1,3],[3,3],[4,0],[4,2]];
 console.log(possibleKnightMoves(chessBoard3));// returns 2 because possible moves are [[2,1],[1,2]]

Please refer the image to understand the possible moves of a knight.

image

Please watch this video for a hint for solving the problem:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment