最简单的bfs搜索,要理解bfs是对所有可能进行遍历,
利用的是搜索的扩散,或者说是种子填充法
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int n,m;
const int Maxsize = 105;
int maze[Maxsize][Maxsize];
int dir[8][2]={{1,1},{1,-1},{-1,1},{-1,-1},{1,0},{-1,0},{0,-1},{0,1}};
typedef struct
{
int x,y;
}node;
int main()
{
void bfs(node start);
char ch;
int cnt;
node start;
while(scanf("%d %d",&n,&m)!=EOF)
{
cnt = 0;
memset(maze,0,sizeof(maze));
for(int i = 0 ; i < n ; i ++)
{
getchar();
for(int j = 0 ; j < m ; j++)
{
scanf("%c",&ch);
if(ch == '.') //记录矩阵的信息。
{
maze[i][j] = 1;
}
}
}
for(int i = 0 ; i < n ; i++)
{
for(int j = 0 ; j < m ; j++)
{
if(!maze[i][j])
{
start.x = i;start.y = j; //每出现一次可以搜索的点,用bfs对其八个方向进行全搜索
maze[i][j] = 1;//对矩阵的信息进行修改,一次可使“一块”搜索修改完毕
bfs(start);
cnt++;
}
}
}
printf("%d\n",cnt);
}
return 0;
}
void bfs(node start)
{
node pre,cur;
pre = start;
queue<node>q;
q.push(pre);
while(!q.empty())
{
pre = q.front();
q.pop();
for(int i = 0 ; i < 8 ; i++)
{
cur.x = pre.x + dir[i][0];
cur.y = pre.y + dir[i][1];
if(maze[cur.x][cur.y])continue;
if(cur.x < 0 || cur.x >=n || cur.y < 0 || cur.y >= m)continue;
maze[cur.x][cur.y] = 1;
q.push(cur);
}
}
}