题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=3309
题意:和基础bfs不一样的就是多了一个,于是就增加相应的属性就好了
简单的搜索题,需要注意的细节多
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<map>
using namespace std;
const int maxn = 30;
int n, m, ans;
char Map[maxn][maxn];
bool vis[maxn][maxn][maxn][maxn];
int xx[4] = {0, 1, 0, -1};
int yy[4] = {1, 0, -1, 0};
struct P
{
int x[2], y[2];
bool ok[2];
int step;
}node;
int BFS()
{
vis[node.x[0]][node.y[0]][node.x[1]][node.y[1]] = 1;
queue<P> Q;
Q.push(node);
while(!Q.empty())
{
P cur = Q.front();
Q.pop();
for(int i = 0; i < 4; i++)
{
P tmp(cur);
if(!tmp.ok[0] && Map[tmp.x[0] + xx[i]][tmp.y[0] + yy[i]] != '*')
{
tmp.x[0] += xx[i];
tmp.y[0] += yy[i];
}
if(!tmp.ok[1] && Map[tmp.x[1] + xx[i]][tmp.y[1] + yy[i]] != '*')
{
tmp.x[1] += xx[i];
tmp.y[1] += yy[i];
}
if(vis[tmp.x[0]][tmp.y[0]][tmp.x[1]][tmp.y[1]] || vis[tmp.x[1]][tmp.y[1]][tmp.x[0]][tmp.y[0]]) continue;
if(tmp.x[0] == tmp.x[1] && tmp.y[0] == tmp.y[1] && Map[tmp.x[0]][tmp.y[0]] != 'H'/* && (!tmp.ok[0] || !tmp.ok[1])*/) continue;
tmp.step = cur.step + 1;
vis[tmp.x[0]][tmp.y[0]][tmp.x[1]][tmp.y[1]] = 1;
if(tmp.x[0] == tmp.x[1] && tmp.y[0] == tmp.y[1])//样例一的情况
{
Q.push(tmp);
continue;
}
for(int t = 0; t < 2; t++)
{
if(Map[tmp.x[t]][tmp.y[t]] == 'H')
{
tmp.ok[t] = 1;
}
}
if(tmp.ok[0] && tmp.ok[1])
{
return tmp.step;
}
Q.push(tmp);
}
}
return 0;
}
int main()
{
int T;
while(cin >> T)
{
while(T--)
{
node.ok[0] = 0;
node.ok[1] = 0;
memset(vis, 0, sizeof(vis));
cin >> n >> m;
int cnt = 0;
for(int i = 0; i < n; i++)
{
scanf("%s", Map[i]);
for(int j = 0; j < m; j++)
{
if(Map[i][j] == 'B')
{
node.x[cnt] = i;
node.y[cnt++] = j;
node.step = 0;
}
}
}
if(ans = BFS())
{
cout << ans << endl;
}
else
{
cout << "Sorry , sir , my poor program fails to get an answer." << endl;
}
}
}
return 0;
}