# 搜索基础之红与黑

1
‘.’：黑色的瓷砖；
2
‘#’：白色的瓷砖；
3
‘@’：黑色的瓷砖，并且你站在这块瓷砖上。该字符在每个数据集合中唯一出现一次。

``````6 9
....#.
.....#
......
......
......
......
......
#@...#
.#..#.
0 0``````

``45``

``````#include<stdio.h>
char a[21][21];
int i,m,n,x,y,h,num;
int dp(int i,int j)
{
if(a[i][j]=='#'||i<0||j<0||i>=m||j>=n)return;
if(a[i][j]=='.'||a[i][j]=='@')
{
num++;
a[i][j]='#';
dp(i+1,j);
dp(i,j+1);
dp(i-1,j);
dp(i,j-1);
}
}
int main()
{
while(scanf("%d%d",&n,&m)&&n!=0&&m!=0)
{
num=0;
for(i=0;i<m;i++)
scanf("%s",a[i]);
for(i=0;i<m;i++)
for(h=0;h<n;h++)
if(a[i][h]=='@')
{
dp(i,h);
break;
}
printf("%d\n",num);
}
return 0;
}
``````

``````#include <iostream>
#include <cmath>
#include <cstring>
#include <stdio.h>
using namespace std;

char maze[25][25];
bool visited[25][25];
int ROW,COL;
int sx,sy;
int dirx[] = {-1,1,0,0};
int diry[] = {0,0,-1,1};
int num;
void DFS(int x,int y )
{
for( int i = 0 ; i < 4 ; i++ ){
int row = x + dirx[i];
int col = y + diry[i];
if(row <= 0 || row > ROW || col <= 0 || col > COL )
continue;
if( !visited[row][col] && maze[row][col] == '.') {
visited[row][col] = true;
num++;
DFS(row,col);
}
}
}
int main()
{
while( cin >> COL >> ROW )
{
if( COL == 0 && ROW == 0 )
break;
for( int i = 1 ; i <= ROW ; i++ )
for( int j = 1 ; j <= COL ; j++){
cin >> maze[i][j];
if( maze[i][j] == '@' ){
sx = i;
sy = j;
}
}
memset(visited,false,sizeof(visited));
num = 1 ;
visited[sx][sy] = true;
DFS(sx,sy);
cout << num << endl;
}
return 0;
}
``````