Given two integers N, M denoting N×M chessboard, the task is to count the number of ways a knight can reach (N, M) starting from (0, 0). Since the answer can be very large, print the answer modulo 109+7.
Input: N =3, M= 3
Two ways to reach (3, 3) form (0, 0) are as follows:
(0, 0) → (1, 2) → (3, 3)
(0, 0) → (2, 1) → (3, 3)
Input: N=4, M=3
Explanation: No possible way exists to reach (4, 3) form (0, 0).
Approach: Idea here is to observe the pattern that each move increments the value of the x-coordinate + value of y-coordinate by 3. Follow the steps below to solve the problem.
- If (N + M) is not divisible by 3 then no possible path exists.
- If (N + M) % 3==0 then count the number of moves of type (+1, +2) i.e, X and count the number of moves of type (+2, +1) i.e, Y.
- Find the equation of the type (+1, +2) i.e. X + 2Y = N
- Find the equation of the type (+2, +1) i.e. 2X + Y = M
- Find the calculated values of X and Y, if X < 0 or Y < 0, then no possible path exists.
- Otherwise, calculate (X+Y)CY.
Below is the implementation of the above approach:
Time Complexity: O(X + Y + log(mod)).
Auxiliary Space: O(1)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Minimum steps to reach target by a Knight | Set 1
- Minimum steps to reach target by a Knight | Set 2
- Puzzle | Can a Knight reach bottom from top by visiting all squares
- Possible moves of knight
- Find minimum moves to reach target on an infinite line
- Minimum moves to reach target on a infinite line | Set 2
- The Knight's tour problem | Backtracking-1
- Probability of Knight to remain in the chessboard
- Warnsdorff's algorithm for Knight’s tour problem
- Number of blocks in a chessboard a knight can move to in exactly k moves
- Count ways to reach the n'th stair
- Count number of ways to reach a given score in a Matrix
- Count ways to reach Nth Stairs by taking 1 and 2 steps with exactly one 3 step
- Count ways to reach the Nth stair using multiple 1 or 2 steps and a single step 3
- Count ways to reach the nth stair using step 1, 2 or 3
- Number of ways to reach Nth floor by taking at-most K leaps
- Number of ways to reach the end of matrix with non-zero AND value
- Find the number of ways to reach Kth step in stair case
- Number of ways to reach (M, N) in a matrix starting from the origin without visiting (X, Y)
- Number of ways to reach (X, Y) in a matrix starting from the origin
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.