After a long time of trying to solve this problem, I was excited to finally have a solution that seemed to work.
I quickly submitted the solution, but to my great surprise, I obtained a TLE. I quickly searched through the code for anything suspicious, but I could not find anything — it seems to be very clearly O(n^2), with n at most 5000... but it still takes far too long: running it on my computer it seemed to take more than 1 second for the loop where I simply initialize all the values to Infinity!
Does anybody know why it would take so long to do such a simple task as this? What am I missing here?