HDU 1312

http://acm.hdu.edu.cn/showproblem.php?pid=1312

'.'可以走,'#'不可以走 '@'是起点 问最多走多少步

就是坐标问题 弄的有点纠结   以后得养成好习惯   不然被坐标绕晕了

代码(

bfs版)  

#include<iostream>
#include<queue>
#include<cstring>
using namespace std;
char ch[22][22];
int r,c;
int XX[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
struct node{int x,y;};
int bfs(int bx,int by,int Sum)
{
int k;
int xx,yy;
node t,tt;
queue<node>qu;
t.x=bx,t.y=by;
qu.push(t);
while(!qu.empty())
{
t=qu.front();
qu.pop();
for(k=0;k<4;k++)
{
xx=t.x+XX[k][1],yy=t.y+XX[k][0];
if(xx>=0&&xx<c&&yy>=0&&yy<r&&ch[xx][yy]!='#')
{
Sum++;
ch[xx][yy]='#';
tt.x=xx,tt.y=yy;
qu.push(tt);
}
}
}

return Sum;

}
int main()
{
int i,j,bx,by,Sum;
while(cin>>c>>r&&c&&r)//c列 r行
{
memset(ch,0,sizeof(ch));
// memset(visit,0,sizeof(visit));
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
cin>>ch[j][i];
if(ch[j][i]=='@')
{
bx=j,by=i;
ch[j][i]='#';
}

}


Sum=1;

cout<< bfs(bx,by,Sum)<<endl;
}
return 0;
}

代码(dfs版):

#include<iostream>
using namespace std;
char ch[22][22];
int r,c,bx,by,sum;
struct node{int x,y;};
int XX[4][2]={{-1,0},{0,-1},{0,1},{1,0}};
void dfs(int bx,int by)
{
sum++;
ch[bx][by]='#';
int k,xx,yy;
for(k=0;k<4;k++)
{ xx=bx+XX[k][1],yy=by+XX[k][0];
if(xx>=0&&xx<c&&yy>=0&&yy<r&&ch[xx][yy]!='#')
dfs(xx,yy);
}
}

int main()
{
int i,j;
while(cin>>c>>r&&c&&r)
{
for(i=0;i<r;i++)
for(j=0;j<c;j++)
{
cin>>ch[j][i];
if(ch[j][i]=='@')
{
bx=j,by=i;
}
}
sum=0;
dfs(bx,by);
cout<<sum<<endl;
}
return 0;
}



posted @ 2011-11-28 00:17  快乐.  阅读(229)  评论(0编辑  收藏  举报