地址:
点击打开链接
这个题就是判断边界的时候需要判断一个整体,其他的时候没什么区别。主要区别在于判断越界,判断是否访问过。依旧是BFS
#include<iostream>
#include<cstring>
#include<cstdio>
#include<queue>
#define inf 0x3f3f3f3f
#define MAX 110
#define repf(i,from ,to) for(int i =from ; i <to ; i++)
using namespace std;
char Map[MAX][MAX];
int Vis[MAX][MAX];
int n,m,time ,magicNum;
int dir[4][2]={{0,1,},{0,-1},{1,0},{-1,0}};
struct Node {
int X[21],Y[21];
int num ;
int time ;
friend bool operator <(Node a ,Node b)
{
return a.time>b.time ;
}
};
bool inMap(int x ,int y)
{
if(x<0||x>=n||y<0||y>=m)
return false ;
return true ;
}
int dfs(Node start)
{
memset(Vis,0,sizeof(Vis));
Vis[start.X[0]][start.Y[0]]=1;
Node now ,next ;
priority_queue<Node> Q;
Q.push(start);
while (!Q.empty())
{
now = Q.top();
Q.pop();
repf(i,0,now.num)
{
if( Map[now.X[i]][now.Y[i]]== 'Q')
{
return now.time;
}
}
for(int i = 0 ;i< 4; i ++)
{
next = now ;
bool flag = true ;
repf(j , 0 ,now.num)
{
next.X[j] = now.X[j]+dir[i][0];
next.Y[j] = now.Y[j]+dir[i][1];
// cout << next.X[j] <<" " << next.Y[j]<<endl;
if(!inMap(next.X[j],next.Y[j])||Map[next.X[j]][next.Y[j]]=='O')
{
flag = false ;
break;
}
}
if(!flag)
{
continue ;
}
if(!Vis[next.X[0]][next.Y[0]])
{
Vis[next.X[0]][next.Y[0]] = 1 ;
next.time++;
Q.push(next);
}
}
}
return -1;
}
int main()
{
Node start ;
while (cin>>n>>m)
{
if(m==0&&n==0) break ;
int index = 0 ;
repf(i,0,n)
{
repf(j,0,m)
{
cin>>Map[i][j];
if(Map[i][j]=='D')
{
start.X[index]=i;
start.Y[index++]=j;
}
}
}
start.num = index ;
start.time = 0;
int res = dfs(start);
if(res==-1)
{
cout <<"Impossible"<<endl;
}else {
cout << res<<endl;
}
}
}