非常经典的DFS题目,因为此系列中有许多与该题类似的题目,在此便不再赘述。
#include<iostream>
#include<cstring>
#include<fstream>
using namespace std;
int m, n;
const int MAX = 500;
const int dir[8][2] = { { -1,0 },{ 1,0 },{ 0,1 },{ 0,-1 },{ -1,-1 },{ -1,1 },{ 1,-1 },{ 1,1 } };
char chess[MAX][MAX];
bool visit[MAX][MAX];
bool isbound(int a, int b)
{
if (a<0 || b<0 || a>=m || b>=n)
return 1;
else return 0;
}
void dfs(int x, int y)
{
for (int i = 0; i < 8; ++i)
{
if (chess[x + dir[i][0]][y + dir[i][1]] == '*') continue;
if (isbound(x + dir[i][0], y + dir[i][1])) continue;
if (visit[x + dir[i][0]][y + dir[i][1]]) continue;
visit[x + dir[i][0]][y + dir[i][1]] = 1;
dfs(x + dir[i][0], y + dir[i][1]);
}
}
int main()
{
//ifstream cin("aaa.txt");
while (cin >> m >> n&&m != 0 && n != 0)
{
memset(visit, 0, sizeof(visit));
for (int i = 0; i < m; ++i)
for (int j = 0; j < n; ++j)
cin >> chess[i][j];
int ans = 0;
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
if (chess[i][j] == '@'&&!visit[i][j])
{
visit[i][j] = 1;
dfs(i, j);
++ans;
}
}
cout << ans << endl;
}
return 0;
}
480

被折叠的 条评论
为什么被折叠?



