VOOZH about

URL: https://www.geeksforgeeks.org/dsa/possible-moves-knight/

⇱ Possible moves of knight - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Possible moves of knight

Last Updated : 20 Mar, 2023

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. 

Examples: 

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) and (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 the number of valid moves. A move will be invalid if: 

  1. A block is already occupied by another piece. 
  2. Move is out of the chessboard.

Implementation:


Output
4

Time Complexity: O(1) 
Auxiliary Space: O(1)

Comment
Article Tags: