Given a matrix mat[][], pair of indices X and Y, the task is to find the number of moves to bring all the non-zero elements of the matrix to the given cell at (X, Y).
A move consists of moving an element at any cell to its four directional adjacent cells i.e., left, right, top, bottom.
Examples:
Input:_ mat[][] = {{1, 0}, {1, 0}}, X = 1, Y = 1_
Output:_ 3_
Explanation:
Moves required =>
For Index (0, 0) => 2
For Index (1, 0) => 1
Total moves required = 3
Input:_ mat[][] = {{1, 0, 1, 0}, {1, 1, 0, 1}, {0, 0, 1, 0}}, X = 1, Y = 3_
Output:_ 13_
Approach: The idea is to traverse the matrix and for each non-zero element of the matrix find the distance of the current cell(say (A, B)) to the destination cell (X, Y) of the matrix as:
moves = abs(x - i) + abs(y - j)
The summation of all the distance by the above formula for all non-zero elements is the required result.
#greedy #mathematical #matrix #algorithms