随机漫步模拟
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范围。
容错代码不想写- -!
在矩形的房间里,铺有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范围。
容错代码不想写- -!
相关文章推荐
- MFC中使用OLE/COM操作EXCEL的方法
- Linux中执行shell脚本的4种方法总结
- 论文笔记 Visualizing and understanding convolutional networks
- 第9周项目2 - 对称矩阵压缩存储的实现与应用(2).cpp
- Android捕获异常处理——UncaughtExceptionHandler
- (java)Length of Last Word
- 117 Populating Next Right Pointers in Each Node II
- ajax+json+Struts2实现list传递实例讲解
- 文章标题
- Java Web系列:Java Web 项目基础
- 第9周项目2 - 对称矩阵压缩存储的实现与应用(1).cpp
- NPM vs Bower 的区别
- Struts2获取request的几种方式汇总(list对象获取)
- 查找
- UML包图&实现图
- POJ1745Divisibility(01背包思想)
- MyEclipse 10中对web.xml使用Format报错
- python的生成器
- leetcode刷题日记——Excel Sheet Column Number
- 关于git的常用方法,多账号以及一些规范(更新)