一个小岛,表示为一个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);//比較函数不能是成员函数,详细參考该链接

};

bool operator<(const position lhs,const position& rhs)

{

return lhs.x < rhs.x;

}

double TheDieIsland(int N,int x,int y,int n,map& hashMap)

{

position p(x,y,n);

map::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 hashMap;

return TheDieIsland(N,x,y,n,hashMap);

}如有问题,请指正,谢谢

查看原文