Oil Deposits:
题目链接:https://vjudge.net/problem/HDU-1241
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.
题面翻译:
@表示油田,如果两个油田对角线/水平/竖直方向上相邻视为同一块油田,问油田共有几块?
更直接翻译:求连通块个数
分析:
求连通块个数首先想到并查集,但是这题用搜索显然更为简单,是搜索的经典入门模板题了;
思路很简单,双重循环寻找没被标记过的油田,找到后就沿八个方向去搜索,搜到的地方做个标记。
深搜广搜都可,dfs做法代码如下:
#include<iostream>
#include<cstdio>
#include<queue>
#include<string.h>
#include<string>
#include<algorithm>
#define inf 0x3f3f3f3f
using namespace std;
int direct[8][2]={{0,1},{0,-1},{1,0},{-1,0},{1,-1},{1,1},{-1,1},{-1,-1}};
int vis[105][105];
char grid[105][105];
int block_num;
int n,m;
typedef struct{
int x;
int y;
}pos;
void dfs(pos node){
for(int i=0;i<8;i++){
pos New=node;
New.x+=direct[i][0];
New.y+=direct[i][1];
if(New.x<=n&&New.x>=1&&New.y<=m&&New.y>=1&&!vis[New.x][New.y]&&grid[New.x][New.y]=='@'){
vis[New.x][New.y]=1;
dfs(New);
}
}
}
int main()
{
while(cin>>n>>m&&n&&m){
memset(vis,0,sizeof(vis));
block_num=0;
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++)
cin>>grid[i][j];
for(int i=1;i<=n;i++)
for(int j=1;j<=m;j++){
if(grid[i][j]=='@'&&!vis[i][j]){
block_num++;
pos start;
start.x=i;
start.y=j;
dfs(start);
}
}
cout<<block_num<<endl;
}
return 0;
}