InputThe input file contains one or more grids. Each grid begins with a line containing m and n, the number of rows and columns in the grid, separated by a single space. If m = 0 it signals the end of the input; otherwise 1 <= m <= 100 and 1 <= n <= 100. Following this are m lines of n characters each (not counting the end-of-line characters). Each character corresponds to one plot, and is either `*‘, representing the absence of oil, or `@‘, representing an oil pocket.
OutputFor each grid, output the number of distinct oil deposits. Two different pockets are part of the same oil deposit if they are adjacent horizontally, vertically, or diagonally. An oil deposit will not contain more than 100 pockets.
Sample Input
1 1 * 3 5 *@*@* **@** *@*@* 1 8 @@****@* 5 5 ****@ *@@*@ *@**@ @@@*@ @@**@ 0 0
Sample Output
0 1 2 2
注意:相邻是指8个方向
1 #include<iostream> 2 #include<stdio.h> 3 #include<cstring> 4 #include<algorithm> 5 #include<queue> 6 7 using namespace std; 8 9 int dx[8] = {1,-1,0,0,1,1,-1,-1}; 10 int dy[8] = {0,0,1,-1,-1,1,1,-1}; 11 char mp[102][102]; 12 int vis[102][102]; 13 int m, n; 14 15 void dfs(int x, int y) 16 { 17 for(int i = 0; i < 8; ++i) 18 { 19 int xx = x + dx[i]; 20 int yy = y + dy[i]; 21 22 if(xx >= 0 && xx < m && yy >= 0 && yy < n && !vis[xx][yy] && mp[xx][yy] == ‘@‘) 23 { 24 vis[xx][yy] = 1; 25 dfs(xx, yy); 26 } 27 } 28 } 29 30 31 int main() 32 { 33 std::ios::sync_with_stdio(false); 34 while(cin >> m >> n) 35 { 36 if(m == 0) 37 break; 38 for(int i = 0; i < m; ++i) 39 for(int j = 0; j < n; ++j) 40 cin >> mp[i][j]; 41 memset(vis, 0, sizeof(vis)); 42 int ans = 0; 43 for(int i = 0; i < m; ++i) 44 { 45 for(int j = 0; j < n; ++j) 46 { 47 if(mp[i][j] == ‘@‘ && !vis[i][j]) 48 { 49 vis[i][j] = 1; 50 dfs(i, j); 51 ans++; 52 } 53 54 } 55 } 56 cout << ans << endl; 57 } 58 59 60 61 return 0; 62 }
原文:https://www.cnblogs.com/FengZeng666/p/11518395.html