/* Oil Deposits Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) Total Submission(s): 37990 Accepted Submission(s): 22039 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 ****@ *@@*@ *@**@ @@@*@ @@**@ Sample Output: 0 1 2 2 */ #include<cstdio> #include<cstring> #include<algorithm> #include<iostream> #include<string> #include<vector> #include<stack> #include<bitset> #include<cstdlib> #include<cmath> #include<set> #include<list> #include<deque> #include<map> #include<queue> using namespace std; const int M=100; const int N=100; char maps[M][N]; int visited[M][N]; void dfs(int i,int j) { ++visited[i][j]; for(int x=-1;x<=1;x++) for(int y=-1;y<=1;y++) { if(maps[i+x][j+y]=='@'&&visited[i+x][j+y]==0) { dfs(i+x,j+y); } } } int main() { int m,n; while(scanf("%d %d",&m,&n)==2&&m&&n) { for(int i=0;i<m;i++) scanf("%s",maps[i]); memset(visited,0,sizeof(visited)); int answer=0; for(int i=0;i<m;i++) for(int j=0;j<n;j++) { if(maps[i][j]=='@'&&visited[i][j]==0) { answer++; dfs(i,j); } } cout<<answer<<endl; } return 0; }
比较水的一道题,难度主要在于英语阅读。这道题的思路很简单,对于首先发现是@的格子,我们有理由认为在该格子的八连通区域内很可能还有另外的@(这有点像我玩MineCraft时的挖矿过程,在发现矿产的方块周围的相邻方块很大概率还能发现同类矿产)。所以很容易想到要使用深度优先遍历检索八连通区域内的格子。涉及到dfs则必然使用递归来简化代码结构(不考虑内存限制)。所以主要代码结构就是大循环遍历找@,找到后就dfs,并且用一个标志数组来记录下访问过的格子就行了。因为这道题我第一次写完代码就AC了,所以代码中就不加注释了。
tz@COI HZAU
2018/3/21