A题意:给你个黑白矩阵,每次黑的周围一圈会变黑,求多少次之后全黑。n <= 1000
解:BFS即可。
1 #include <bits/stdc++.h> 2 3 const int N = 1010; 4 const int dx[] = {1, 0, -1, 0}; 5 const int dy[] = {0, 1, 0, -1}; 6 7 struct Node { 8 int x, y; 9 Node(int X = 0, int Y = 0) { 10 x = X; 11 y = Y; 12 } 13 }; 14 15 int vis[N][N], d[N][N]; 16 char str[N]; 17 std::queue<Node> Q; 18 19 int main() { 20 21 int n, m, ans = 0; 22 scanf("%d%d", &n, &m); 23 for(int i = 1; i <= n; i++) { 24 scanf("%s", str + 1); 25 for(int j = 1; j <= m; j++) { 26 if(str[j] == '#') { 27 Q.push(Node(i, j)); 28 vis[i][j] = 1; 29 d[i][j] = 0; 30 } 31 } 32 } 33 34 while(Q.size()) { 35 int x = Q.front().x, y = Q.front().y; 36 Q.pop(); 37 for(int i = 0; i < 4; i++) { 38 int tx = x + dx[i], ty = y + dy[i]; 39 if(tx < 1 || ty < 1 || tx > n || ty > m || vis[tx][ty]) { 40 continue; 41 } 42 vis[tx][ty] = 1; 43 d[tx][ty] = d[x][y] + 1; 44 Q.push(Node(tx, ty)); 45 ans = std::max(ans, d[tx][ty]); 46 } 47 } 48 printf("%d\n", ans); 49 return 0; 50 }