![]() |
VOOZH | about |
Given a starting position in a 2D matrix representing a grid of points, the task is to find the minimum number of steps required for a knight to collect the maximum points, subject to the following conditions:
Note: The knight moves exactly the same as the knight on a chess board. Please follow 0-based indexing.
Examples:
Input: n = 9, m = 10, start_x = 4, start_y = 5
arr =
0 0 0 2 0 2 0 2 0 0
0 0 2 0 2 0 2 0 2 0
0 2 0 0 1 2 0 0 0 2
0 0 2 0 2 0 2 0 2 0
0 2 0 2 0 0 0 2 0 2
0 0 2 0 2 0 2 0 2 0
0 2 0 0 0 2 0 0 0 2
0 0 2 0 2 0 2 0 2 0
0 0 0 2 0 2 0 2 0 0
Output: 1
Explanation: minimum knight have to take 1 steps to gain maximum points.
- Initially, the knight has 0 coins, he will take 1 step to collect 1 point (sum of cells denoted in red color).
- Now in the second step, he can collect points from all the cells colored green i.e. 64 points.
- But with his magical power, at the 1st step, he can fetch points from the (1 + 1)th step. Therefore he can collect 1 + 64 coins at step 1 only. Hence answer is 1.
Input: n = 3, m = 3, start_x = 2, start_y = 1
arr =
7 6 8
9 1 4
6 2 8
Output: 0
Explanation: Initially, the knight has 2 points, or more formally we can say that at the 0th step knight has 2 points.
- In the first step, he can collect points from cells (0, 0) and (0, 2) i.e. 15 points.
- In the second step, he can collect points from cells (1, 0) and (1, 2) i.e. 13 coins.
- In the third step, he can collect points from cells (2, 0) and (2, 2) i.e. 14 points.
- In the fourth step, he can collect points from the cell (0, 1) i.e. 6 points.
- So in each step, he can collect coins like -You can see in the below image Knight can collect 15 coins in the 0th step only
Approach: To solve the problem follow the below idea:
The idea is to to explore all the valid neighboring cells from the current cell using BFS traversal, and keep track of the visited cells. Now, calculate the total points collected by the knight, and add the points to a list at each level. After the BFS completes, find the maximum sum of points that can be collected and return the level at which the maximum sum is collected.
Below are the steps for the above approach:
Below is the code for the above approach:
1
Time Complexity: O(N*M)
Auxiliary Space: O(N*M)
Related Articles: