码迷,mamicode.com
首页 > 其他好文 > 详细

待字闺中之死亡小岛分析

时间:2014-07-17 19:19:22      阅读:253      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   color   strong   os   

一个小岛,表示为一个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);
}
如有问题,请指正,谢谢

待字闺中之死亡小岛分析,布布扣,bubuko.com

待字闺中之死亡小岛分析

标签:style   blog   http   color   strong   os   

原文地址:http://blog.csdn.net/fangjian1204/article/details/37909055

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!