练习二1011

来源:互联网 发布:java 驼峰转下划线 编辑:程序博客网 时间:2024/04/29 22:03

Oil Deposits
Time Limit : 2000/1000ms (Java/Other)   Memory Limit : 65536/32768K (Java/Other)
Total Submission(s) : 48   Accepted Submission(s) : 16
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. <br>
 

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.<br>
 

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.<br>
 

Sample Input
1 1<br>*<br>3 5<br>*@*@*<br>**@**<br>*@*@*<br>1 8<br>@@****@*<br>5 5 <br>****@<br>*@@*@<br>*@**@<br>@@@*@<br>@@**@<br>0 0 <br>
 

Sample Output
0<br>1<br>2<br>2<br>
 

Source
Mid-Central USA 1997
 

Statistic |Submit | Back
题意:
给定若干组矩形行方阵由“@”与“*”组成,寻找其中有多少个“@”块(即“@”相邻的块)。
思路:
先找到第一个@,然后开始深搜,直到这一块搜索完,sum++,再找下一个@。
代码:
#include<iostream>
#include<string.h>
using namespace std;
int dir[8][2]={{-1,0},{1,0},{0,1},{0,-1},{-1,1},{-1,-1},{1,1},{1,-1}};
char oil[110][110];
bool vis[110][110];
int m,n;
bool isbound(int i,int j)
{
 if(i>0&&i<=m&&j>0&&j<=n)
  return true;
 return false;
}
void dfs(int x,int y)
{
 for(int i=0;i<8;i++)
 {
  if(!isbound(x+dir[i][0],y+dir[i][1]))
   continue;
  if(oil[x+dir[i][0]][y+dir[i][1]]=='*')
   continue;
  if(vis[x+dir[i][0]][y+dir[i][1]])
   continue;
  vis[x+dir[i][0]][y+dir[i][1]]=1;
  dfs(x+dir[i][0],y+dir[i][1]);
 }
}
int main()
{
 int k,h;
 while(cin>>m>>n&&(m!=0||n!=0))
 {
  for(k=1;k<=m;k++)
   for(h=1;h<=n;h++)
    cin>>oil[k][h];
   memset(vis,0,sizeof(vis));
   int sum=0;
   for(k=1;k<=m;k++)
       for(h=1;h<=n;h++)
     if(oil[k][h]=='@'&&!vis[k][h])
     {
      vis[k][h]=1;
      dfs(k,h);
                     sum++;
     }
     cout<<sum<<endl;
 }
 return 0;
}

提交该题时发现一个问题,main()函数中的k,h定义在for里面时(for(int k=1.........))会CE。
0 0