您的位置:首页 > 其它

随机漫步模拟

2015-12-17 19:25 190 查看
问题描述:

在矩形的房间里,铺有N*M块瓷砖,现将一只醉酒的蟑螂放在地板中间的一个指定方格里。蟑螂在房间随机从一块瓷砖漫步到另一块瓷砖。假设它可能从所在的瓷砖移动到其周围八块瓷砖中的任何一个(除非碰到墙壁)。那么,它至少接触每块瓷砖一次,将花费多少时间?

#include <iostream>
#include <stdlib.h>
#include <iomanip>
using namespace std;
const int Max=50000;
int room[42][42];
int main()
{
int Count=0,n,m,x,y, //移动总次数,列,行,横、纵坐标。
c=1, //表示有几个格子被走过。
imove[8]={-1,0,1,1,1,0,-1,-1}, //表示上下移动的数组。
jmove[8]={1,1,1,0,-1,-1,-1,0}; //表示左右移动的数组。
cout<<"Please input the room's size\n";
cout<<"Room's row:";
cin>>n;
cout<<"Room's column:";
cin>>m;
cout<<"Please input the horizontal coordinates in the begin:\n";
cin>>x;
cout<<"Please input the longitudinal coordinates in the begin:\n";
cin>>y;
room[y][x]=1;
for(;Count<Max;Count++){
int x1=x,y1=y; //保存初始位置,防止一撞墙位置就丢失。
do{
x=x1,y=y1;
y+=imove[rand()%8];
x+=jmove[rand()%8];
}while(y<1||x<1||y>n||x>m); //随机移动,撞墙重新来。
if(!room[y][x])
c++;
room[y][x]++;
if(c==n*m) break; //填满退出。
}
cout<<"The drunken cockroaches spent "<<Count<<" walking through the house\n";
cout<<"The room is now become:\n";
for(int i1=1;i1<=n;i1++){
for(int j1=1;j1<=m;j1++)
cout<<setiosflags(ios::right)<<setw(4)
<<room[i1][j1];
cout<<endl;
}
}
输入的n,m不超过40,开始点不要超过n,m范围。
容错代码不想写- -!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: