1003. 二哥养细菌

http://acm.sjtu.edu.cn/OnlineJudge/problem/1003

类似BFS扩展的思想:

将第一代细菌位置入队列;

队列中细菌到上下左右没有细菌的位置进行繁殖、更改这些位置的标记(0->1),繁殖出的新一代细菌入栈;

如果栈空,结束,否则队列清空,栈中的新一代细菌入队列;

如果栈空,说明培养皿已经充满了(题目保证最终能够充满培养皿)。

复杂度O(n)。

 1 # include <stdio.h>
 2 
 3 # define N 105
 4 
 5 int A[N][N], L;
 6 int m;
 7 
 8 const int d[][2] = {{-1,0}, {0,-1}, {1,0}, {0,1}};
 9 
10 int x[N*N], y[N*N], top;
11 int s[N*N], t[N*N], cnt;
12 
13 int main()
14 {
15  //  freopen("in.txt", "r", stdin);
16 
17     scanf("%d", &L);
18     top = 0;
19     for (int i = 1; i <= L; ++i) {
20         for (int j = 1; j <= L; ++j) {
21             scanf("%d", &A[i][j]);
22             if (A[i][j] == 1) {
23                 x[top] = i;
24                 y[top] = j;
25                 ++top;
26             }
27         }
28     }
29 
30     m = 0;
31     while (1) {
32         cnt = 0;
33         for (int i = 0; i < top; ++i) {
34             for (int j = 0; j < 4; ++j) {
35                 int nx = x[i]+d[j][0];
36                 int ny = y[i]+d[j][1];
37                 if (0>=nx||nx>L||0>=ny||ny>L) continue;
38                 if (A[nx][ny] == 0) {
39                     s[cnt] = nx;
40                     t[cnt] = ny;
41                     ++cnt;
42                     A[nx][ny] = 1;
43                 }
44             }
45         }
46         if(cnt <= 0) break;
47         for (int i = 0; i < cnt; ++i) {
48             x[i] = s[i];
49             y[i] = t[i];
50         }
51         top = cnt;
52         ++m;
53     }
54 
55     printf("%d
", m);
56 
57     return 0;
58 }
原文地址:https://www.cnblogs.com/txd0u/p/3352328.html