Given a M * N
grid and location of two players p1
and p2
on grid. There are n balls placed on different positions on the grid. Let the location of these balls be B(1), B(2), B(3) ..., B(n)
.
We need to calculate the minumum manhattan distance required to pick all the balls. Balls should be picked in ascending order i.e if B(i)
is picked before B(j)
if i < j
.
Consider the following sample case:
p1 = (1, 1)
p2 = (3, 4)
Lets consider location of balls as
B(1) = (1, 1), B(2) = (2, 1), B(3) = (3, 1), B(4) = (5, 5)
Output will be 5
because p1
will first choose B(1), B(2), B(3)
and p1
will choose B(4)
My Approach
I did a greedy approach and calculated distance of p1
and p2
from a given ball B(i)
(starting from i = 1 to n
) and added the minimum to the output and updated the position of the player accordingly.
But this approach fails for a lot of testcases.
P.S: This question was asked in one of my past interviews and O(n)
solution to this problem is expected.
Edit: More testcases can be like
p1 = (1,1) p2 = (3,5)
B(1) = (3, 3), B(2) = (1, 1), B(3) = (4, 5), B(4) = (2, 1), B(5) = (4, 3).
In this case p1
will choose B(2), B(4)
and p2
will choose B(1), B(3), B(5)
Output will be 8.
p1 = (1,1) p2 = (3,4)
B(1) = (2, 2), B(2) = (3, 2), B(3) = (4, 2), B(4) = (1, 1)
In this case p1
will choose B(4)
and p2
will choose B(1), B(2), B(3)
Output will be 5.
Note: When player chooses a ball he moves to that point.
P.P.S. After discussion I believe no linear-time solution exists to this problem and O(n^2) solution is the best solution available.