【习题9】随机漫步 random walk问题
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX_N 50
#define MAX_ITERATION 50000
int wander[MAX_N][MAX_N] = {0};
int imove[] = {-1, 0, 1, 1, 1, 0, -1, -1};
int jmove[] = {1, 1, 1, 0, -1, -1, -1, 0};
int A[4][3] = {1,2,3,3,4,5,5,6,7,0,1,7};
int B[4][5] = {1,2,3,4,5,0,1,5,6,7,0,1,2,3,7,3,4,5,6,7};
int bugmove(int n, int m, int i, int j);
int nextstep(int n, int m, int i, int j);
int traverse(int n, int m);
int main(void){
int n, m, i, j, steps;
printf("input the board size n*m:\n");
scanf("%d%d",&n,&m);
printf("input the start point [i,j]\n");
scanf("%d%d",&i,&j);
srand((unsigned int)time(NULL));
steps = bugmove(n, m, i, j);
if (steps > 0){
printf("\nThe bug has moved %d steps to traverse the %d*%d board.\n", steps, n, m);
printf("The travers density is as following:\n");
for(i = 0;i < n;i++){
for(j = 0;j < m;j++)
printf("%5d",wander[i][j]);
printf("\n");
}
} else
printf("BUG IS WANDERING...steps = %d\n",steps);
}
int bugmove(int n, int m, int i, int j){
if (i > n || j > m) return -1;
int iteration = 1;
int s;
wander[i][j] = 1;
while (iteration <= MAX_ITERATION){
s = nextstep(n, m, i, j);
if (s == -1) return -1;
i += imove[s];
j += jmove[s];
wander[i][j] += 1;
if (traverse(n, m)) return iteration;
iteration++;
}
if (iteration > MAX_ITERATION){
printf("Amazing! The bug hasn't traverse the board in %d steps.\n", MAX_ITERATION);
return -2;
}
}
int nextstep(int n, int m, int i, int j){
if (i > n || j > m)
return -1;
int flag = 0;
if (i == 0 && j == 0)
flag = 1;
else if (i == 0 && j == m-1)
flag = 2;
else if (i == n-1 && j == m-1)
flag = 3;
else if (i == n-1 && j == 0)
flag = 4;
else if (i == 0 && (j > 0 && j < m-1))
flag = 5;
else if (i == n-1 && (j > 0 && j < m-1))
flag = 6;
else if ((i > 0 && i < n-1) && j == 0)
flag = 7;
else if ((i > 0 && i < n-1) && j == m-1)
flag = 8;
int k, s;
if (flag >= 1 && flag <= 4){
k = rand() % 3;
s = A[flag - 1][k];
} else if (flag >= 5 && flag <= 8){
k = rand() % 5;
s = B[flag - 5][k];
} else
s = rand() % 8;
return s;
}
int traverse(int n, int m){
for(int i = 0;i < n;i++)
for(int j = 0;j < m;j++)
if (!wander[i][j])
return 0;
return 1;
}