~cpp
#include <iostream>
#include<cstdlib> // For rand() and srand()
#include<ctime> //For time(0)
using namespace std;
int count[40][20]; //maximum size of the count array is 40*20
//move dirction
int imove[8] = {-1,0,1,1,1,0,-1,-1};
int jmove[8] = {1,1,1,0,-1,-1,-1,0};
//variable
int counter = 0;
int ibug, jbug; //start point(x,y)
int n,m; //array's range is n*m
//funtion
void input();
void init();
void move();
bool is_end();
void output();
int main()
{
init(); //inital count array
input(); //input the board size
move(); //cackroach move the board
output(); //print result about count_array and Total_count_Number
return 0;
}
void init() //inital count array
{
for(int i=0; i<n; i++)
{
for (int j=0; j<m;j++)
count[i][j] = 0;
}
}
void input()
{
cout<<"input size of the board : "; //input m and n (for make M*N array)
while(cin>>n>>m)
{
//size range : 2<n<=40 and 2<m<=20
if( ( n<=2 || n>40 ) || ( m<=2 || m>40 ) )
{
cout<<"the board's size is out of range. try again :";
continue;
}
break;
}
cout<<"input start point : ";
while(cin>>ibug>>jbug)
{
//point range : 2<n<=40 and 2<m<=20
if( ( ibug<=0 || ibug>40 ) || ( jbug<=0 || jbug>40 ) )
{
cout<<"start point is out of range. try again:";
continue;
}
break;
}
}
void move()
{
count[ibug][jbug]++; //inital the start point
srand(time(0)); //for make random number
int k; //random variable
while( is_end() )
{
k = rand()%8; // random value range :0~7
//the board's range
if( (ibug+imove[k]) >=0 && (ibug+imove[k]) < n
&& (jbug+jmove[k])>=0 && (jbug+jmove[k]) < m )
{
//벌레의 이동한 좌표
ibug += imove[k];
jbug += jmove[k];
count[ibug][jbug]++;//check the visiting room.
counter++;
}
else
continue;//범위밖으로 나가면 다시 랜덤값 결정.
}
}
bool is_end() //각방을 다 방문했는지를 검사
{
if(counter >= 50000) //excute limitation
return false;
for (int i =0; i<n ; i++)
{
for(int j=0; j<m; j++)
{
if(count[i][j] == 0)
return true;
}
}
return false;
}
void output()
{
cout<<"Total moving Number : "<<counter<<endl;
for(int i =0; i<n; i++)
{
for(int j=0; j<m; j++)
{
cout.width(3);
cout<<count[i][j]<<" ";
}
cout<<endl;
}
}