Two balls move on a grid for T seconds with different random rules; compute the probability they collide, to 4 decimals.
Medium7ProbabilityDynamic programmingSimulationNo attempts yetTime limit1sMemory limit256 MBMirko and Slavko are in their fourth year of high school and compete for the title of best mathematician in the school. Besides mathematics, Mirko spends his free time on computer science and Slavko on physics. Both of them passed every mathematics exam of the school year with a perfect score, so their teacher gave them one hard problem: whoever gives the more precise answer earns the title of best mathematician in the school. The problem is as follows.
A board has R rows and S columns (R×S cells). The centers of every two cells that share a side are connected by a groove, and there is a magnet under some of the cells. Two balls, A and B, are placed on the board and move like this:
The available directions are those among up, down, left, and right that do not leave the board. Both balls move at the same time, once per second.
The balls collide if, in the same second, they move onto the same cell or meet on a groove (that is, they swap cells). Starting on the same cell is not a collision. What is the probability that the balls collide within the first T seconds?
Slavko decided to solve the problem by measurement. He placed balls A and B on the given cells of a prepared board (using plastic balls instead of glass ones), waited T seconds, and repeated this 1000 times. He then divided the number of runs in which the balls collided by the total number of runs. Mirko heard about this, but he knows that trial and measurement will not give a precise enough answer. He decided to write a program that computes the answer precisely to 4 decimal places and so wins the title of best mathematician.
Write a program like Mirko's that computes this probability.
The first line contains three integers R, S, and T: the number of rows of the board, the number of columns, and the number of seconds the balls move (2≤R,S≤10, 1≤T≤1000).
The second line contains four integers Ar, As, Br, Bs. Ball A starts in row Ar, column As, and ball B starts in row Br, column Bs (1≤Ar,Br≤R, 1≤As,Bs≤S). Rows are numbered from 1 starting at the top, and columns from 1 starting at the left.
Each of the next R lines contains S characters. P is a cell without a magnet, and M is a cell with a magnet.
Print the probability that the balls collide within the given time on a single line, rounded to 4 decimal places. Always print exactly 4 digits after the decimal point (for example, 0.2500).
The exact probability is guaranteed to be more than 10−7 away from every rounding boundary (the midpoint between two consecutive multiples of 0.0001).