随机漫步问题 :醉酒的蟑螂

来源:互联网 发布:unix怎么安装软件 编辑:程序博客网 时间:2024/04/27 22:19
#include <stdio.h>#include <stdlib.h>#include <time.h>#define ROW 15#define COL 15#define MAX 50000typedef struct { int x, y; }Bugs; // bug's position 虫子的位置int Matrix[ROW][COL];// Original is 0  初始值为0int imove[8] = {-1, 0, 1, 1, 1, 0, -1, -1,}, jmove[8] = {1, 1, 1, 0, -1, -1, -1, 0}; void show();int notzero(); // if all element of Matrix nonzero return 1, else return 0; 若有所有元素都为非0,return 1 否则 return 0int main(){int count = 0, k = 0, tx, ty;Bugs ibug;ibug.x = 10, ibug.y = 10;tx = ibug.x, ty = ibug.y;srand(time(NULL)); // rand seedclock_t start, end;double duration = 0;start = 0, end = 0;start = clock();// Matrix degree count 计算矩阵密度while(count < MAX){if(notzero() == 1) // each of all has been moved  移动到了每个区break;k = rand() % 8;if(ibug.x+imove[k] >= 0 && ibug.y+jmove[k] >= 0 &&ibug.x+imove[k] < ROW && ibug.y+jmove[k] < COL){ibug.x += imove[k];ibug.y += jmove[k];tx = ibug.x;ty = ibug.y;Matrix[tx][ty]++;}else{ibug.x = tx;ibug.y = ty;continue;}system("cls");show();++count;}end = clock();duration = ((double)(end-start)/CLK_TCK);printf("%d times\n", count);printf("%lf seconds\n", duration);return 0;}void show(){int i, j;for(i = 0; i < ROW; i++){for(j = 0; j < COL; j++)printf("%4d", Matrix[i][j]);printf("\n");}}int notzero(){int i, j;for(i = 0; i < ROW; i++){for(j = 0; j < COL; j++)if(Matrix[i][j] == 0)return 0;}return 1;}