POJ 2386
题意:所有连在一起(八方)的W表示一个湖,计算所有的湖。
思路:找到一个W后dfs,并把能搜索到的w全部记为已经遍历, 每次dfs时令ans++(湖的个数),最终输出ans即可,这里对W进行dfs时除了边界条件只让其搜索包围它的W.
也可以直接bfs。
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
#define PI acos(-1.0)
#define eps 1e-10
#define INF 0x7fffffff
#define debug(x) cout << "--------------> " << x << endl
typedef long long LL;
typedef unsigned long long ULL;
using namespace std;
char graph[108][108];
int vis[108][108];
int n, m, ans;
int dx[8] = {1,1,0,-1,-1,-1,0,1}, dy[8] = {0,1,1,1,0,-1,-1,-1};
void dfs(int x,int y)
{
for(int i = 0; i < 8; ++i)
{
int xx = x+dx[i], yy = y+dy[i];
if(xx >=0 && xx < n && yy >= 0 && yy < m)
{
if(graph[xx][yy] == 'W' && !vis[xx][yy])
{
vis[xx][yy] = 1;
dfs(xx,yy);
}
}
}
}
int main()
{
memset(vis,0,sizeof(vis));
int ans = 0;
scanf("%d%d",&n,&m);
for(int i = 0; i < n; ++i)
{
scanf("%s",&graph[i]);
}
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < m; ++j)
{
if(graph[i][j] == 'W' && !vis[i][j])
{
vis[i][j] = 1;
dfs(i, j);
ans++;
}
}
}
printf("%d",ans);
return 0;
}
#include <iostream>
#include <iomanip>
#include <cstring>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <set>
#include <map>
#include <list>
#include <stack>
#include <deque>
#include <queue>
#include <vector>
#include <algorithm>
#include <functional>
#define debug(x) cout << "--------------> " << x << endl
using namespace std;
const double PI = acos(-1.0);
const double eps = 1e-10;
const long long INF = 0x7fffffff;
const long long MOD = 1000000007;
const int MAXN = 100 + 7;
int n, m;
class Point
{
public:
Point(int a, int b):x(a),y(b){};
int x, y;
};
char gra[MAXN][MAXN];
bool vis[MAXN][MAXN];
int dx[] = {0, -1, -1, -1, 0, 1, 1, 1};
int dy[] = {1, 1, 0, -1, -1, -1, 0, 1};
int ans = 0;
bool isValidRoad(int x, int y)
{
return x >=0 && x < n && y >= 0 && y < m && !vis[x][y];
}
void BFS(int x, int y)
{
if(isValidRoad(x, y) && gra[x][y] == 'W')
{
ans++;
vis[x][y] = true;
Point p(x, y);
queue<Point> q;
q.push(p);
while(!q.empty())
{
Point P = q.front();
q.pop();
for(int i = 0; i < 8; ++i)
{
Point PP(P.x + dx[i], P.y + dy[i]);
if(isValidRoad(PP.x , PP.y) && gra[PP.x][PP.y] == 'W')
{
q.push(PP);
vis[PP.x][PP.y] = true;
}
}
}
}
return ;
}
int main()
{
memset(gra, 0, sizeof(gra));
memset(vis, false, sizeof(vis));
scanf("%d%d", &n, &m);
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < m; ++j)
{
cin >> gra[i][j];
}
}
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < m; ++j)
{
if(gra[i][j] == 'W' && !vis[i][j])
BFS(i, j);
}
}
printf("%d\n", ans);
return 0;
}