太久没有做过搜索相关的题目,基本的代码实现都要忘记了,作为复习吧,分别用栈来模拟深搜,队列来模拟广搜,借助于递归(系统栈)来模拟搜索三种方法来求解问题。作为一个ACMer,一题多解是最基本的素质!
题目链接:http://acm.nefu.edu.cn/JudgeOnline/problemShow.php?problem_id=465
题目代码实现:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <stack>
using namespace std;
struct node
{
int x,y;
};
stack<node>sta; ///用栈来模拟搜索
int n;
char str[15][15];
int dx[5]= {-1,1,0,0};
int dy[5]= {0,0,-1,1};
int ans;
int solve(int st,int sd)
{
node temp;
temp.x=st;
temp.y=sd;
sta.push(temp);
str[temp.x][temp.y]='#';///在入栈的时候就要
while(!sta.empty())
{
node now;
now=sta.top();
sta.pop();
int nx,ny;
for(int i=0; i<4; i++)
{
nx=now.x+dx[i];
ny=now.y+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<n && str[nx][ny]=='.')
{
ans++;
node tmp;
tmp.x=nx;
tmp.y=ny;
//cout<<nx<<" "<<ny<< " "<<ans<<endl;
//cout<<str[nx][ny]<<endl;
sta.push(tmp);
str[tmp.x][tmp.y]='#';
}
}
}
return ans;
}
queue<node>que; ///用队列来模拟搜索
int solve1(int sx,int sy)
{
int nx,ny;
node temp;
temp.x=sx;
temp.y=sy;
que.push(temp);
while(!que.empty())
{
node now;
now=que.front();
que.pop();
for(int i=0;i<4;i++)
{
nx=now.x+dx[i];
ny=now.y+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<n && str[nx][ny]=='.')
{
ans++;
node tmp;
tmp.x=nx;
tmp.y=ny;
que.push(tmp);
str[tmp.x][tmp.y]='#';
}
}
}
return ans;
}
void solve2(int sx,int sy)
{
int nx,ny;
for(int i=0;i<4;i++)
{
nx=sx+dx[i];
ny=sy+dy[i];
if(nx>=0 && nx<n && ny>=0 && ny<n && str[nx][ny]=='.')
{
ans++;
solve2(nx,ny);
}
}
}
int main()
{
//int sum;
while(scanf("%d",&n)!=EOF)
{
//sum=0;
ans=0;
memset(str,0,sizeof(str));
for(int i=0; i<n; i++)
{
for(int j=0;j<n;j++)
{
scanf(" %c",&str[i][j]);
}
}
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(str[i][j]=='@')
{
solve1(i,j);
break;
}
}
}
printf("%d\n",ans);
}
return 0;
}