题意是,一个地图,起点为'@',求和它连着的空地有多少。很简单的搜索题,用了深搜和广搜。注意题上的数据给的是列和行,不是我们所习惯的行和列。
AC代码:
代码语言:javascript复制#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
char MAP[25][25];
int n,m,step,S_x,S_y;
void dfs(int x,int y){
if(MAP[x][y] == '#') return ;
if(x < 0 || y < 0 || x >= m || y >= n) return ;
step ;
MAP[x][y] = '#';
dfs(x,y 1);
dfs(x,y-1);
dfs(x 1,y);
dfs(x-1,y);
}
int main()
{
while(~scanf("%d%d",&n,&m)){
if(n == 0 && m == 0) break;
for(int i=0;i<m;i ){
scanf("%s",MAP[i]);
}
for(int i=0;i<m;i ){
for(int j=0;j<n;j ){
if(MAP[i][j] == '@'){
S_x = i;
S_y = j;
}
}
}
step = 0;
dfs(S_x,S_y);
printf("%dn",step);
}
return 0;
}
BFS代码:
代码语言:javascript复制#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
using namespace std;
char MAP[25][25];
int vis[25][25];
struct Node{
int x,y;
}Now,Next,S;
int dir[4][2] = {1,0,0,1,-1,0,0,-1};
int n,m,step;
void bfs(){
queue<Node> q;
memset(vis,0,sizeof(vis));
q.push(S);
while(!q.empty()){
Now = q.front();
q.pop();
for(int i=0;i<4;i ){
Next.x = Now.x dir[i][0];
Next.y = Now.y dir[i][1];
if(Next.x>=0&&Next.y>=0&&Next.x<m&&Next.y<n&&MAP[Next.x][Next.y]=='.'&&!vis[Next.x][Next.y]){
vis[Next.x][Next.y] = 1;
step ;
q.push(Next);
}
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m)){
if(n == 0 && m == 0) break;
for(int i=0;i<m;i ){
scanf("%s",MAP[i]);
}
for(int i=0;i<m;i ){
for(int j=0;j<n;j ){
if(MAP[i][j] == '@'){
S.x = i;
S.y = j;
}
}
}
step = 0;
bfs();
printf("%dn",step 1);
}
return 0;
}