POJ 1562 Oil Deposits
Oil Deposits
Time Limit: 1000MS | Memory Limit: 10000K | |
Total Submissions: 8588 | Accepted: 4804 |
Description
The GeoSurvComp geologic survey company is responsible for detecting underground oil deposits. GeoSurvComp works with one large rectangular region of land at a time, and creates a grid that divides the land into numerous square plots. It then analyzes each plot separately, using sensing equipment to determine whether or not the plot contains oil. A plot containing oil is called a pocket. If two pockets are adjacent, then they are part of the same oil deposit. Oil deposits can be quite large and may contain numerous pockets. Your job is to determine how many different oil deposits are contained in a grid.
Input
The input 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.
Output
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
Source
广搜即可。维护一个队列,未被访问的且为‘@’的顶点入队,然后弹出的同时让其所有邻接顶点入队,那么队列为空的时候,说明一片油田的所有点被标记为 visited。用一个全局变量控制计数即可。郁闷的是位移数组自己把逗号打成了小数点,然后字体太小一直没看出来,查了好久的错…
1 #include <iostream> 2 #include <string> 3 #include <stack> 4 #include <queue> 5 #include <vector> 6 #include <cstdlib> 7 #include <cstdio> 8 9 using namespace std; 10 11 bool field[105][105]; 12 bool visited[105][105]; 13 14 int dy[8] = {-1,0,1,1,1,0,-1,-1}; 15 int dx[8] = {-1,-1,-1,0,1,1,1,0}; 16 17 queue< pair<int,int> > q; 18 int countfield(0); 19 20 void bfs(int bx,int by) 21 { 22 int x = q.front().first,y = q.front().second; 23 for(int i(0);i != 8;++i) 24 if(x+dx[i] <= bx-1 && x+dx[i] >= 0 && y+dy[i] >= 0 && y+dy[i] <= by-1) 25 if(field[x+dx[i]][y+dy[i]] && !visited[x+dx[i]][y+dy[i]]) 26 { 27 q.push(make_pair(x+dx[i],y+dy[i])); 28 visited[x+dx[i]][y+dy[i]] = true; 29 } 30 q.pop(); 31 if(q.empty()) 32 countfield++; 33 else 34 bfs(bx,by); 35 } 36 37 int main(void) 38 { 39 int row,col; 40 char tmp; 41 while(cin >> row >> col && (row && col)) 42 { 43 getchar(); 44 for(int i(0);i != row;++i) 45 { 46 for(int j(0);j != col;++j) 47 { 48 cin >> tmp; 49 if(tmp == '@') 50 field[i][j] = true; 51 else 52 field[i][j] = false; 53 } 54 getchar(); 55 } 56 for(int i(0);i != row;++i) 57 for(int j(0);j != col;++j) 58 if(field[i][j] && !visited[i][j]) 59 { 60 q.push(make_pair(i,j)); 61 visited[i][j] = true; 62 bfs(row,col); 63 } 64 cout << countfield << endl; 65 countfield = 0; 66 for(int i(0);i != row;++i) 67 for(int j(0);j != col;++j) 68 visited[i][j] = false; 69 } 70 71 return 0; 72 }