題意:
要確認畫面中有幾隻Eagles,每個pixel如果是'1'代表為一隻Eagles,但上下左右(包含斜角共8個方向)相連的'1'只能算是同一隻。
想法:
使用DFS找'1'有幾個區域。
1 #include <cstdio> 2 using namespace std; 3 4 char image[30][30]; 5 6 void DFS(int &n, int i, int j) 7 { 8 image[i][j] = '0'; 9 if (i-1 >= 0 && image[i-1][j] == '1') DFS(n, i-1, j); 10 if (i+1 < n && image[i+1][j] == '1') DFS(n, i+1, j); 11 if (j-1 >= 0 && image[i][j-1] == '1') DFS(n, i, j-1); 12 if (j+1 < n && image[i][j+1] == '1') DFS(n, i, j+1); 13 if (i-1 >= 0 && j-1 >= 0 && image[i-1][j-1] == '1') DFS(n, i-1, j-1); 14 if (i-1 >= 0 && j+1 < n && image[i-1][j+1] == '1') DFS(n, i-1, j+1); 15 if (i+1 < n && j-1 >= 0 && image[i+1][j-1] == '1') DFS(n, i+1, j-1); 16 if (i+1 < n && j+1 < n && image[i+1][j+1] == '1') DFS(n, i+1, j+1); 17 } 18 19 int main() 20 { 21 // freopen ("input.txt","rt",stdin); 22 int n,Case = 1; 23 while (scanf("%d", &n) != EOF){ 24 getchar(); 25 for (int i = 0; i < n; ++i) 26 gets(image[i]); 27 int num = 0; 28 for (int i = 0; i < n; ++i) 29 for (int j = 0; j < n; ++j) 30 if (image[i][j] == '1'){ 31 DFS(n, i, j); 32 ++num; 33 } 34 printf("Image number %d contains %d war eagles. ", Case++, num); 35 } 36 return 0; 37 }