Problem Description
After a long drastic struggle with himself, LL decide to go for some snack at last. But when steping out of the dormitory, he found a serious problem : he can’t remember where is the canteen… Even worse is the campus is very dark at night. So, each time he move, he check front, back, left and right to see which of those four adjacent squares are free, and randomly walk to one of the free squares until landing on a canteen.
Input
Each case begin with two integers n and m ( n<=15,m<=15 ), which indicate the size of the campus. Then n line follow, each contain m characters to describe the map. There are 4 different type of area in the map:
‘@’ is the start location. There is exactly one in each case.
‘#’ is an impassible square.
‘$’ is a canteen. There may be more than one in the campus.
‘.’ is a free square.
Output
Output the expected number of moves required to reach a canteen, which accurate to 6 fractional digits. If it is impossible , output -1.
Sample Input
1 2
@ 22@..
1 3
@#$
Sample Output
1.000000
4.000000
-1
大致题意:n*m的地图有一个起点,多个出口,有些格子有障碍物不能走,每次上下左右走一格,问从起点走到出空的期望步数是多少。
思路:地图n*m看成一个个格子,编号0,1,2,3…n*m-1, 那么坐标i,j的格子编号为 i*m+j
EK表示编号为K的格子到一个出口的期望步数
那么EK=0, K这里为出口的编号
我们要求的则是EK, K这里为起点的编号
由一个状态可以走向其他状态,假设当前K可以向三个方向走,
那么 EK= (EK(a) + EK(b) +EK(c)) /3 +1
一般的 EK=(Enext1+Enext2+Enext3+……Ecnt)/ cnt+1
整理得 Enext1+Enext2+Enext3+…Ecnt - EK*cnt= - cnt
对每个EK(K=0,1,2,3…n*m-1),都建立这样的一个等式,那么可以列出 n*m个方程,然后采用高斯消元,求出E(起点)
其中有 n*m个方程,n*m个变量
a[i][j]代表第i个式子(从0开始),第j个未知数的系数(从0开始),其中EK为未知数
a[0][0]