待字闺中之死亡小岛分析
2016-04-02 18:48
369 查看
一个小岛,表示为一个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。详细代码例如以下:
当他走出小岛,就意味着死亡。如果他要走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); }如有问题,请指正,谢谢
相关文章推荐
- zoj3878——Convert QWERTY to Dvorak
- Micro2440开发板启动Linux
- [NOIP2013][CODEVS3287]货车运输(kruskal+树上倍增)
- Java并发编程系列之八:wait()、notify()和notifyAll()
- 第九章 原型模式
- 可视化深度学习和人类感知Visualizing Representations: Deep Learning and Human Beings-1
- Spring学习---1
- URL链接中汉字乱码转UTF-8和gb2312
- 一步一步利用django创建博客应用(二)
- zoj2876——May Day Holiday(算星期)
- Java内存区域划分
- ubuntu下安装编译链
- 快速排序
- Micro2440数据传输---串口通信
- ROS基础环境的配置
- select标签中显示指定内容
- shell 脚本执行日志通用模块
- 《古文字学》学习
- Android开发:解决android:gravity不能居中问题
- UFLDL Tutorial 笔记