1. Question description:
Black and white imagesTime limit (Common/Java): 1000 ms/3000 Ms memory limit: 65536 Kbyte
Total submit: 282 accepted: 82
Description
Enter an n × n black/white image (1 indicates black, 0 indicates white). The task is to count the number of eight connected blocks. If two black grids have public edges or public vertices, they belong to the same eight-connected block. The figure shown in is composed of three eight connected parts.
Input
Enter a positive integer n (n ≤ 1st) in row 700, followed by N rows. Each row is a string consisting of n 0 or 1.
Output
Number of eight connected blocks in the input black/white image
Sample Input
6
100100
001010
000000
110000
111000
010100
Sample output
3
Source
Liu rujia: algorithm competition entry-level classic
2. Train of Thought Analysis:
First, we can see that this problem is related to the recursion of graphs. We have similar operations for each blacklist:
1. First, check whether the 1-contained data has been accessed. To determine whether the data has been accessed, you can use an equal-size two-dimensional array to identify each data;
2. Whether the eight data around the data is 1. If it is changed to 1, it will not be considered later.
3: Code display:
1 # include <stdio. h> 2 # include <memory. h> 3 const int maxn = 1000; 4 void DFS (int I, Int J); 5 Int vis [maxn] [maxn], mat [maxn] [maxn]; 6 char s [maxn]; 7 int main () 8 {9 int N; 10 // DFS [1] [1]; 11 while (scanf ("% d ", & N )! = EOF) 12 {13 int COUNT = 0, num = 1; 14 memset (VIS, 0, sizeof (VIS); 15 memset (MAT, 0, sizeof (MAT); 16 for (INT I = 1; I <= N; I ++) // first input data, and pay attention to edge issues 17 {18 scanf ("% s", S); 19 for (Int J = 0; j <n; j ++) 20 mat [I] [J + 1] = s [J]-'0'; 21 memset (S, '\ 0', sizeof (s )); 22} 23 for (INT I = 1; I <= N; I ++) 24 for (Int J = 1; j <= N; j ++) 25 {26 if (MAT [I] [J] & (! Vis [I] [J]) 27 {28 count ++; 29 DFS (I, j); 30} 31} 32 printf ("% d \ n ", count); 33} 34 return 0; 35} 36 void DFS (int I, Int J) 37 {38 If (! Mat [I] [J] | Vis [I] [J]) return; 39 vis [I] [J] = 1; 40 DFS (I-1, J-1 ); DFS (I-1, J); DFS (I-1, J + 1); 41 DFS (I, J-1); DFS (I, j + 1); 42 DFS (I + 1, j-1); DFS (I + 1, J); DFS (I + 1, J + 1); 43 44}
Summary:
1. Both BFS and DFS should pay attention to the boundary issue and should not go beyond the scope specified by data. This question is about adding an invisible white lattice to the border.
2. recursive calls will push local variables (I, j, I-1, J-1 ·) into the frame stack, if the image is too large, there is a risk of overflow.