![]() |
VOOZH | about |
In Geekland, a knight is positioned at coordinates (start_x, start_y) within an N x M matrix. Each cell in the matrix contains a certain number of points. The knight has a unique ability to collect all the points from cells that can be reached in exactly i steps without revisiting any cell. Additionally, the knight possesses magical powers, allowing it to fetch points from future steps. If the knight can collect y points in the xth step, it can also fetch all the points it will collect in the (x + y)th step, and so on.
For instance, if the knight can collect 1 point in the 1st step, it will also collect all points at the 2nd step (1+1), and if it can collect 3 points in the (1+1)th step, it will also fetch all points at the (1+1+3)th step. Therefore, even at the 1st step, the knight can collect an overall total of 1+3=4 points if there are no points available at the (1+1+3)th step.
The task is to determine the minimum number of steps required for the knight to collect the maximum possible points. The knight moves exactly like a chessboard knight, following 0 indexing.
Note: The knight can move in an L-shaped pattern, similar to a knight's movement in chess.
Example:
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: 1Input: int n2 = 3, m2 = 3, start_x2 = 2, start_y2 = 1;
arr =
{7, 6, 8},
{9, 1, 4},
{6, 2, 8} };
Output: 0
Approach:
The idea is to use a Breadth-First Search (BFS) Algorithm to explore the grid. It maintains a queue of cells to visit, starting with the knight’s initial position. For each cell, it calculates the points that can be collected from that cell and updates the total points.
The BFS algorithm will continues until all cells have been visited. The points from each cell are added to the total points, and if the points from a cell plus its index is less than the size of the grid, the points are added again.
Finally, iterates over the points collected at each step and returns the index of the step that collected the maximum points..
Steps-by-step approach:
Below is the implementation of the above approach:
The maximum score starting from the given position is: 1
Time Complexity: O(N*M) The breadth-first search (BFS) explores each cell at most once, where N is the number of rows and M is the number of columns in the grid.
Auxiliary Space: O(N*M)