隨機漫步問題 :醉酒的蟑螂

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


#define ROW 15
#define COL 15
#define MAX 50000
typedef struct { int x, y; }Bugs; // bug's position 蟲子的位置

int Matrix[ROW][COL];			// Original is 0  初始值爲0
int 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 0
int 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 seed


	clock_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;
}
 


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章