10703
题目
[3.4] 设计程序,模拟“生命游戏”:
- 世界由
个方格组成,每个方格有两种状态:要么有生命,要么无生命; - 每个方格周围的 8 个方格(边 5 个,角 3 个)称为它的“邻居”;
- 在每代演化中,如果某方块有生命且其邻居中的 2 个或 3 个有生命,则该方块在下一代中保持有生命;如果该方块无生命且其邻居中的 3 个有生命,则该方块在下一代中变为有生命;其余情况则保持不变。
首先输入世界大小
答案
c
#include <stdio.h>
#include <stdlib.h>
int **allocate_world(int size) {
int **world = (int **)malloc(size * sizeof(int *));
if (world == NULL) {
exit(1);
}
for (int i = 0; i < size; i++) {
world[i] = (int *)malloc(size * sizeof(int));
if (world[i] == NULL) {
exit(1);
}
}
return world;
}
void free_world(int **world, int size) {
for (int i = 0; i < size; i++) {
free(world[i]);
}
free(world);
}
void print_world(int **world, int size) {
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
printf("%d", world[i][j]);
if (j < size - 1) {
printf(" ");
}
}
printf("\n");
}
}
int count_live_neighbors(int **world, int size, int row, int col) {
int live_count = 0;
for (int i = -1; i <= 1; i++) {
for (int j = -1; j <= 1; j++) {
if (i == 0 && j == 0) {
continue;
}
int neighbor_row = row + i;
int neighbor_col = col + j;
if (neighbor_row >= 0 && neighbor_row < size &&
neighbor_col >= 0 && neighbor_col < size) {
if (world[neighbor_row][neighbor_col] == 1) {
live_count++;
}
}
}
}
return live_count;
}
int main() {
int n;
scanf("%d", &n);
int **current_world = allocate_world(n);
int **next_world = allocate_world(n);
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", ¤t_world[i][j]);
}
}
int m;
scanf("%d", &m);
for (int generation = 0; generation < m; generation++) {
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
int live_neighbors = count_live_neighbors(current_world, n, i, j);
int current_state = current_world[i][j];
if (current_state == 1 && (live_neighbors == 2 || live_neighbors == 3)) {
next_world[i][j] = 1;
} else if (current_state == 0 && live_neighbors == 3) {
next_world[i][j] = 1;
} else {
next_world[i][j] = 0;
}
}
}
int **temp_world = current_world;
current_world = next_world;
next_world = temp_world;
}
print_world(current_world, n);
free_world(current_world, n);
free_world(next_world, n);
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102