Oil Deposits
Time Limit : 2000/1000ms (Java/Other) Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 43 Accepted Submission(s) : 19
Font: Times New Roman | Verdana | Georgia
Font Size: ← →
Problem 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 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.
Output
For 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
Source
Mid-Central USA 1997
这题其实就是 确定有多少个连通分量
即有多少个独立的@图
深搜和广搜都可以
连通的方向有8个
每检查到一个@ 就可以把他变为* 然后在从这点 扩充;
#include<iostream> #include<stack> #include<algorithm> using namespace std; int n,m; char map[105][105]; int fang[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,-1},{1,1},{-1,1},{-1,-1}}; struct num { int x; int y; }; int main() { while(scanf("%d %d",&n,&m),n>=1&&m>=1) { int number=0; stack<num> st; num now; int i,j; memset(map,'*',sizeof(map)); for(i=0;i<n;i++) { for(j=0;j<m;j++) { cin>>map[i][j]; } }//输入结束 for(i=0;i<n;i++)//开始检测 { for(j=0;j<m;j++) { if(map[i][j]=='@')//该点为@且没走过 { number++; now.x=i; now.y=j; st.push(now);// 为@的点进站; while(!st.empty()) { num now2;//记录出栈的点 now2=st.top(); st.pop(); if(now2.x>=0&&now2.x<n&&now2.y>=0&&now2.y<m)//判断是否越界 { //没有越界 if(map[now2.x][now2.y]=='@')//没有走过 且为@ { map[now2.x][now2.y]='*';//标记//重这个点开始扩充 8个方向 int k=0; for(k=0;k<8;k++) { num now3; now3=now2; now3.x=now3.x+fang[k][0]; now3.y=now3.y+fang[k][1]; st.push(now3); } } } } } } }//检测结束 printf("%d ",number); } return 0; }