No older revisions available
No older revisions available
~cpp
#include <iostream>
#include <ctime>
using namespace std;
void move(int dir);
int check_all(int);
void display(int);
int **walk;
int **check;
int row, col;
int main()
{
int size, i, j;
int end , direct ;
cout << "=random walk problem= \n";
cout << "배열 크기 입력 : " ;
cin >> size;
//동적 배열로 walk판 만듬
walk = new int *[size+2];
for (i=0; i<size+2; i++)
walk[i] = new int[size+2];
//동적배열로 check판 만듬
check = new int *[size+2];
for (i=0; i<size+2; i++)
check[i] = new int[size+2];
//배열 초기화
for(i=0; i<size+2; i++)
for(j=0; j<size+2; j++)
{
if (i==0 || i==size+1 || j==0 || j==size+1)
walk[i][j] = -1;
else
walk[i][j] = 0;
check[i][j] = 0;
}
srand(time(0));
row = (rand() % size)+1;
col = (rand() % size)+1;
do{
direct = rand() % 8; //방향 결정
move(direct); //결정된 방향으로 움직임
end = check_all(size); //모든 판을 다 갔는지 체크
}while(!end);
//결과 출력
display(size);
return 0;
}
int check_all(int size)
{
int sum =0;
for(int i=0; i<size+2; i++)
for(int j=0; j<size+2; j++)
sum += check[i][j];
if(sum == size*size)
return 1;
else
return 0;
}
void move(int dir)
{
switch(dir)
{
case 0 : if (walk[row-1][col] != -1)
{
row--;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 1 : if (walk[row-1][col+1] != -1)
{
row--; col++;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 2 :if (walk[row][col+1] != -1)
{
col++;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 3 : if (walk[row+1][col+1] != -1)
{
row++; col++;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 4: if (walk[row+1][col] != -1)
{
row++;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 5 : if (walk[row+1][col-1] != -1)
{
row++; col--;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 6 : if (walk[row][col-1] != -1)
{
col--;
walk[row][col]++;
check[row][col] = 1;
}
break;
case 7 : if (walk[row-1][col-1] != -1)
{
row--; col--;
walk[row][col]++;
check[row][col] = 1; }
break;
}
}
void display(int size)
{
int count = 0;
for(int i=1; i<size+1; i++)
{
for(int j=1; j<size+1; j++)
{
cout << walk[i][j] << "\t";
count += walk[i][j];
}
cout <<"\n";
}
cout << "총 움직인 횟수 : " << count << "\n";
}
음..방향을 배열루 입력시키믄 switch문을 길게 안써두 되는군..
그리구 check판이 없어두 끝나는걸 알 수 있을꺼 같다.
고쳐야지..