“.”能走,“#”不能走,“@”为起点,求所有能走到的地方。
BFS:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int w,h;
int dir[4][2]={{0,+1},{-1,0},{0,-1},{+1,0}};
char t[23][23];
bool vis[23][23];
struct type{
int x,y;
}st,now,next;
int bfs()
{
int cnt=1;
queue<type> q;
q.push(st);
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(vis[next.x][next.y]==0) //如果这一步可以走
{
vis[next.x][next.y]=1; //将走过的这块tile标记为1
q.push(next);
cnt++; //可走的tile计数+1
}
}
}
return cnt;
}
int main()
{
while(scanf("%d%d",&w,&h) && (w*h)!=0)
{
for(int i=1;i<=h;i++)
{
scanf("%s",(t[i]+1));
}
//将地图转化为相应的标记数组,所有不能走的、走过的tile均标记为1(包括边界以外的地方以及起点),能走的tile都标记为0
memset(vis,1,sizeof(vis));
for(int i=1;i<=h;i++)
{
for(int j=1;j<=w;j++)
{
if(t[i][j]=='.') vis[i][j]=0;
if(t[i][j]=='#') vis[i][j]=1;
if(t[i][j]=='@') st.x=i,st.y=j,vis[i][j]=1;
}
}
int ans=bfs();
printf("%d\n",ans);
}
}
DFS:
#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int w,h;
int dir[4][2]={{0,+1},{-1,0},{0,-1},{+1,0}};
char t[23][23];
bool vis[23][23];
struct type{
int x,y;
}st,next;
void dfs(int x,int y,int &ans)
{
if(vis[x][y]) return; //如果这个tile走过直接退出函数
vis[x][y]=1; //把这块tile标记为已走过
ans++; //计数+1
for(int i=0;i<4;i++)
{
next.x=x+dir[i][0] , next.y=y+dir[i][1]; //走一步
if(next.x >= 1 && next.x <= h && next.y >= 1 && next.y <= w) //如果走的这一步tile在限定的 w * h 范围内就深搜一下
{
dfs(next.x,next.y,ans);
}
}
}
int main()
{
while(scanf("%d%d",&w,&h) && (w*h)!=0)
{
for(int i=1;i<=h;i++)
{
scanf("%s",(t[i]+1));
}
for(int i=1;i<=h;i++)
{
for(int j=1;j<=w;j++)
{
if(t[i][j]=='.') vis[i][j]=0;
if(t[i][j]=='#') vis[i][j]=1;
if(t[i][j]=='@') st.x=i,st.y=j,vis[i][j]=0;
}
}
int ans=0;
dfs(st.x,st.y,ans);
printf("%d\n",ans);
}
}