# Ants moving on a grid

I got asked this as a programming interview question so the "correct" solution is via simulation, but I'm curious about the existence of an analytic solution.

Two ants start in opposing corners of an 8x8 grid and after each turn, pick a valid direction (N, S, E, W) to move uniformly randomly until they arrive on the same square. What is the expected number of moves?

It seems similar to a number of problems and looks simple enough that I feel there could be an analytic solution, but any approach that I come up with ends up having some flaw that I can't account for.

• Did you get any answer by simulation? – gar Oct 9 '15 at 17:51
• Yes, the solution via simulation is trivial, but not what I'm interested in. – kevmo314 Oct 10 '15 at 16:32
• Okay, wanted to verify my simulation first before going with the analytic one. I am getting about 200 turns, is it what you get too? – gar Oct 10 '15 at 17:09
• Ah, I got ~82 turns. I verified this was correct with someone else who wrote the simulation as well. I don't want to share my code since this is an interview question, but someone posted theirs on a similar question here: gist.github.com/dhalik/51a5c0dc621a43d3bb94 – kevmo314 Oct 10 '15 at 19:13
• Hmm, then it's mistake with my code. Result of that code is close to my analytical answer for a 3x3 board ($\frac{234}{37} \approx 6.324$) – gar Oct 11 '15 at 3:02

## 1 Answer

In principle you can do this using a (rather large) Markov chain. You have $64^2$ states of the form $(i,j,k,l)$ indicating that the ants are at $(i,j)$ and $(k,l)$. If $A$ is the transition matrix then I think you'll need to look at $\frac{d}{dt}(I-tA)^{-1}$ at $t=0$. But $A$ is a $4096\times4096$ (sparse) matrix, so this is a challenge. It would make a great programming problem! 😀

• It should have a simpler solution.. On the second thought, not very likely. – zhoraster Oct 8 '15 at 15:47
• @zhoraster actually I think it does. The ways for ants to meet at time $t$ correspond to paths of length $2t$ from the lower left corner to the upper right. So you only need to consider $64$ states! I'll update when I get time. – Tad Oct 8 '15 at 19:23
• But don't forget that these are very special paths, with certain self-avoidance. – zhoraster Oct 8 '15 at 19:25
• @Tad how would you invert that matrix in a reasonable amount of time? An O(n^3) algorithm would be rather slow. I could see maybe doing it via Cholesky factorization though? – kevmo314 Oct 10 '15 at 16:43