zoukankan      html  css  js  c++  java
  • 待字闺中之死亡小岛分析

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

  • 相关阅读:
    2015 Multi-University Training Contest 5 1007
    2015 Multi-University Training Contest 5 1002
    ZOJ 3261 Connections in Galaxy War (并查集)
    POJ 2492 A Bug's Life (并查集)
    POJ 1733 Parity game (离散化+带权并查集)
    HDU 3172 Virtual Friends (并查集节点统计)
    HDU 2473 Junk-Mail Filter (并查集节点删除)
    hdu3047 Zjnu Stadium && HDU 3038 How Many Answers Are Wrong (带权并查集)
    HDU 1272 小希的迷宫
    poj 3620 Avoid The Lakes(dfs)
  • 原文地址:https://www.cnblogs.com/zfyouxi/p/5348017.html
Copyright © 2011-2022 走看看