Oil Deposits

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 4219    Accepted Submission(s): 2415


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

 

那个图格式有点不对   ,所以发个原题链接    看原题就懂题意了。 http://acm.hdu.edu.cn/showproblem.php?pid=1241

              和黑白图像八连块的题一样。是一道DFS的入门题。 所以说的不多。思路在代码的注释中。

               思路和代码如下。

// Status_AC Time_15MS Memory_340k
#include<stdio.h>
#include<string.h>
char gird[102][102];  //二维字符数组  存格子的符号
int vir[102][102];    //标记数组。记录格子是否已访问过
void dfs(int i,int j)
{
	if(gird[i][j]=='*'||vir[i][j]) return;   //如果是* 或 访问过直接返回
	vir[i][j]=1;    //记录访问
	dfs(i-1,j-1);  dfs(i-1,j); dfs(i-1,j+1);  //对周围格子递归查找
	dfs(i,j-1);   dfs(i,j+1);
	dfs(i+1,j-1);  dfs(i+1,j);  dfs(i+1,j+1);
}

int main()
{
	//freopen("1.in","r",stdin);
	int n,m,i,j,count;
	while(scanf("%d%d",&n,&m)!=EOF&&(n||m))
	{
		count=0;
	    memset(vir,1,sizeof(vir));    //将所有格子初始为访问过。
		
		//为了方便判断边界,所以将周围虚拟一圈已访问的格子
		for(i=1;i<=n;i++)
		{
			scanf("%s",gird[i]);
			for(j=m;j>=1;j--) 
			{
				gird[i][j]=gird[i][j-1];  //将所有字符向后推一个
				vir[i][j]=0;     //将这些有字符的格子标记为未访问
			}
		}

		for(i=1;i<=n;i++)
			for(j=1;j<=m;j++)
				if(!vir[i][j]&&gird[i][j]=='@')  //如果有未访问过的@ ,则是新的八连块。
				{
					count++;        
					dfs(i,j);         //同时搜索此八连块的所有@。将之标记为已访问
				}
		printf("%d\n",count);
	}
	return 0;
}


 

 

                     ps: 今天上午大物,c++的课,加上一下午都在搞算法。晚上兴致也很浓,但明天还得高数,大学英语,电路。 坑爹。没办法。只能去睡了。