就是求图中有多少个水洼。对图进行dfs遍历,并把是水洼的地方全部标记。然后从下一个是水哇的地方再进行dfs。
1 #include <cstdio> 2 #include <iostream> 3 #include <cstring> 4 using namespace std; 5 int graph[105][105]; 6 int sum; 7 bool vis[105][105]; 8 int dx[] = {-1, -1, -1, 0, 0, 1, 1, 1}; 9 int dy[] = {-1, 0, 1, -1, 1, -1, 0 ,1}; 10 int row, col; 11 12 bool check(int x, int y) 13 { 14 if( x >= 0 && x < row && y >= 0 && y < col) 15 return true; 16 return false; 17 } 18 19 void dfs(int x, int y) 20 { 21 int ix, iy; 22 for(int i = 0; i < 8; i++) 23 { 24 ix = x + dx[i]; 25 iy = y + dy[i]; 26 if(!vis[ix][iy] && check(ix, iy) && graph[ix][iy] == 1) 27 { 28 vis[ix][iy] = true; 29 dfs(ix, iy); 30 } 31 } 32 } 33 int main() 34 { 35 //freopen("in.txt", "r", stdin); 36 cin >> row >> col; 37 getchar(); 38 memset(vis, false, sizeof(vis)); 39 40 char c; 41 for(int i = 0; i < row; i ++) 42 { 43 for(int j = 0; j < col; j++) 44 { 45 c = getchar(); 46 graph[i][j] = (c == '.') ? 0 : 1; 47 } 48 getchar(); 49 } 50 sum = 0; 51 52 for(int i = 0; i < row; i ++) 53 { 54 for(int j = 0; j < col; j++) 55 { 56 if(graph[i][j] == 1 && vis[i][j] == false) 57 { 58 sum++; 59 vis[i][j] = true; 60 dfs(i, j); 61 } 62 } 63 } 64 65 cout << sum << endl; 66 return 0; 67 }