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:**

_ mat[][] = {{1, 0}, {1, 0}}, X = 1, Y = 1_Input:

_ 3_Output:

Explanation:

Moves required =>

For Index (0, 0) => 2

For Index (1, 0) => 1

Total moves required = 3

_ mat[][] = {{1, 0, 1, 0}, {1, 1, 0, 1}, {0, 0, 1, 0}}, X = 1, Y = 3_Input:

_ 13_Output:

**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

2.15 GEEK