Minimum Moves (Grid Path)

combinatoricsdynamic programming

How can i find the number of minimum moves for a given path with nxn grid to bring both players at each end together on any node?

Below example is for 6×6 grid and each player can move only within given direction. So for the first direction lets say if we move "left" only green can move left and then if we move "up" both red and green can move up and so on. Can we find the minimum number of moves required to move each circle to the same node? What could be the type of algorithm that I should be searching for (shortest path, longest path etc.)

enter image description here

Thanks

Best Answer

This seems like a job for dynamic programming. This means that we do the problem backwards in a sense. In any case where both players can move in the same direction, we obviously want to move in that direction. When we have a choice of two directions to move, we want to move in the direction that leaves the position requiring fewer steps.

Therefore, we start by computing the minimum number of steps required to move from positions where the players are close together, and keep track of the results. Then we increase the distance by $1$, and use the saved values to compute the new move requirements.

We can modify this to keep track of what the best move is in each case.

I wrote the following python script to do this.

green = 'XLULDLLLURRUURDRUULLLDDLUUURRRRRDDDDY'
table = green.maketrans('LRUD', 'RLDU')
red = green.translate(table)
N = len(green)
distance = { }
step = { }

for n in range(N):
    distance[n,n] = 0
for k in range(1, N):
    for n in range(N-k):
        if green[n+1] == red[n+k-1]:
            distance[n,n+k] = 1 + distance[n+1,n+k-1]
            step[n,n+k] = green[n+1]
        elif distance[n,n+k-1] <= distance[n+1,n+k]:
            distance[n,n+k] = 1 + distance[n,n+k-1]
            step[n,n+k] = red[n+k-1]
        else:
            distance[n,n+k] = 1 + distance[n+1,n+k]
            step[n,n+k] = green[n+1]

print(f'{distance[0,N-1]} steps required')
G = 0
R = N-1
steps = ''
while G < R:
    s = step[G,R]
    steps += s
    if s == green[G+1]:
        G += 1
    if s == red[R-1]:
        R  -= 1
print(steps)

In the green path, X and Y are just placeholders for the starting positions, and U,D,L,R are the moves needed to get to that cell. The red path is the same as the green, with the directions reversed.

The program produces the following output:

26 steps required
UUUULULDLLLDDDRUURRUURDDLU 

So, if I haven't made any mistakes, $26$ steps are required, the first $4$ of which are "up", and so on.

I haven't checked this script carefully at all. You should probably make some small cases that you can solve by hand, and test the script on them. Let me know of any problems, please.