12.kuangbin 简单搜索 - HDU - 1241 Oil Deposits
题意:
想要去发展自己的宝藏产业,她的宝藏储存地为nm的矩形,每个位置用代表空的地方,@代表有宝藏的地方。某些宝藏处相连(最近的八个位置,上下左右,斜线),他们被称为同一块宝藏。问有多少块宝藏处?
题解:
这题是8个方向的dfs,当这个格子是@时候,就要从这个格子开始进行dfs,dfs就是处理连起来的@,计数+1。再找下一个是@的格子,再处理掉与此相连的@,计数+1。如此往复,直到处理完整个地图,搜索结束。(细节详情请看代码)
#include<cstdio>
#include<iostream>
#include<cstring>
#include<string>
#include<cmath>
#include<algorithm>
#define IOS ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define ll long long
//#define int ll
#define INT_MAX 0x3f3f3f3f
#define INT_MIN 0xc0c0c0c0
using namespace std;
int read()
{
int w = 1, s = 0;
char ch = getchar();
while (ch < '0' || ch>'9') { if (ch == '-') w = -1; ch = getchar(); }
while (ch >= '0' && ch <= '9') { s = s * 10 + ch - '0'; ch = getchar(); }
return s * w;
//最大公约数
}int gcd(int x,int y) {
if(x<y) swap(x,y);//很多人会遗忘,大数在前小数在后
//递归终止条件千万不要漏了,辗转相除法
return x % y ? gcd(y, x % y) : y;
}
int lcm(int x,int y)//计算x和y的最小公倍数
{
return x * y / gcd(x, y);//使用公式
}
//------------------------ 以上是我常用模板与刷题几乎无关 ------------------------//
const int N = 110;
char Map[N][N];
int dir[8][2] = {{0, 1} , {1, 1} , {1, 0} , {1, -1} , {0, -1} , {-1, -1} , {-1, 0} , {-1, 1}};//注意8个方向
int n, m;
void dfs(int x , int y)
{
Map[x][y] = '*';
//8个方向
for(int i = 0 ; i < 8 ; ++i) {
int mx = x + dir[i][0];
int my = y + dir[i][1];
//判断越界情况
if(mx >= 0 && mx <= n && my >= 0 && my <= m) {
if(Map[mx][my] == '@') {
dfs(mx,my);
}
}
}
}
int main()
{
while(~scanf("%d %d" , &n , &m) && n && m) {
int ans = 0;
//采用双重for循环遍历整个地图
for (int i = 0 ; i < n ; ++i) {
for (int j = 0 ; j < m ; ++j) {
cin >> Map[i][j];
}
}
for (int i = 0 ; i < n ; ++i) {
for (int j = 0 ; j < m ; ++j) {
//当且仅当格子是@并且没有访问过
if (Map[i][j] == '@') {
dfs(i , j);
ans++;
}
}
}
printf("%d\n", ans);
}
return 0;
}