Problem Description
Homura wants to help her friend Madoka save the world. But because of the plot of the Boss Incubator, she is trapped in a labyrinth called LOOPS.
The planform of the LOOPS is a rectangle of R*C grids. There is a portal in each grid except the exit grid. It costs Homura 2 magic power to use a portal once. The portal in a grid G(r, c) will send Homura to the grid below G (grid(r+1, c)), the grid on the right of G (grid(r, c+1)), or even G itself at respective probability (How evil the Boss Incubator is)!
At the beginning Homura is in the top left corner of the LOOPS ((1, 1)), and the exit of the labyrinth is in the bottom right corner ((R, C)). Given the probability of transmissions of each portal, your task is help poor Homura calculate the EXPECT magic power she need to escape from the LOOPS.
Input
The following R lines, each contains C*3 real numbers, at 2 decimal places. Every three numbers make a group. The first, second and third number of the cth group of line r represent the probability of transportation to grid (r, c), grid (r, c+1), grid (r+1, c) of the portal in grid (r, c) respectively. Two groups of numbers are separated by 4 spaces.
It is ensured that the sum of three numbers in each group is 1, and the second numbers of the rightmost groups are 0 (as there are no grids on the right of them) while the third numbers of the downmost groups are 0 (as there are no grids below them).
You may ignore the last three numbers of the input data. They are printed just for looking neat.
The answer is ensured no greater than 1000000.
Terminal at EOF
Output
Sample Input
Sample Output
6.000
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=1005;
int n,m;
double p[maxn][maxn][3],f[maxn][maxn];
double dp(int x,int y)
{
if (x<0||x>n||y<0||y>m||1-p[x][y][0]<1e-6) return f[x][y]=0;
if (f[x][y]>1e-6) return f[x][y];
f[x][y]=(2+p[x][y][1]*dp(x,y+1)+p[x][y][2]*dp(x+1,y))/(1-p[x][y][0]);
return f[x][y];
}
int main()
{
while (cin>>n>>m)
{
for (int i=1;i<=n;i++)
for (int j=1;j<=m;j++)
for (int k=0;k<3;k++) scanf("%lf",&p[i][j][k]);
memset(f,0,sizeof(f));
printf("%.3lf\n",dp(1,1));
}
return 0;
}