<Fundamentals of Data Structures in C> 2.8 附加习题

【习题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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值