待字闺中之死亡小岛分析

来源:互联网 发布:数据挖掘与gis的关系 编辑:程序博客网 时间:2024/04/28 06:58

一个小岛,表示为一个N×N的方格,从(0,0)到(N-1, N-1),一个人站在岛上,位置(x, y),他可以上下左右走,一步一个格子,他选择上下左右的可能性是一样的。当他走出小岛,就意味着死亡。假设他要走n步,请问他死亡的概率有多大?请写出求解代码。

分析

遇到这样的问题,就试着走几步好了。当一个人在(x,y)的时候,假设他此时,死亡的概率为p(x,y,n),然后,他有四种选择,而且是可能性相同,就是说,选择上下左右的概率都是1/4:

选择上边,死亡的概率是多少呢?此时位置为(x, y-1),剩余的步数为n-1,则概率为p(x, y - 1, n - 1)

选择下边同理:概率为p(x, y + 1, n - 1)

选择左边同理:概率为p(x - 1, y, n - 1)

选择右边同理:概率为p(x + 1, y, n - 1)

则,p(x,y,n)=(p(x, y - 1, n - 1) + p(x, y + 1, n - 1) + p(x - 1, y, n - 1) + p(x + 1, y, n - 1))/4,可以表达出递归的形式。

这个题目,看似比较复杂,但是尝试走一步,之后,写出递归表达式了,就比较简单了。递归终止的条件,只要x或者y,满足了小于0或者大于n-1的时候,p=1。具体代码如下:

struct position//记录当前的位置和还需要走的步数{int x;int y;int n;position(int a,int b,int c):x(a),y(b),n(c){}friend bool operator<(const position lhs,const position& rhs);//比较函数不能是成员函数,<a target=_blank href="http://www.cnblogs.com/kevintian/articles/1277700.html">具体参考该链接</a>};bool operator<(const position lhs,const position& rhs){return lhs.x < rhs.x;}double TheDieIsland(int N,int x,int y,int n,map<position,double>& hashMap){position p(x,y,n);map<position,double>::iterator iter = hashMap.find(p);if(iter != hashMap.end())return hashMap[p];//防止递归时重复计算,类似于动态规划的思想if( x < 0 || y < 0 || x > N-1 || y > N-1){return 1;}if( n == 0){return 0;}double probability = (TheDieIsland(N,x-1,y,n-1,hashMap)+TheDieIsland(N,x,y-1,n-1,hashMap)+TheDieIsland(N,x+1,y,n-1,hashMap)+TheDieIsland(N,x,y+1,n-1,hashMap))*0.25;hashMap[p] = probability;//保存已经获得的结果return probability;}double TheDieIsland(int N,int x,int y,int n){if(x < 0 || x > N-1 || y < 0 || y > N-1 || n < 0 || N <= 0)return 0;map<position,double> hashMap;return TheDieIsland(N,x,y,n,hashMap);}
如有问题,请指正,谢谢

3 1
原创粉丝点击