您的位置:首页 > 其它

1572 宝岛地图【预处理+搜索】

2018-01-18 17:00 495 查看
题目链接:点击打开链接
思路:直接搜索的话会超时。由于指令中许多可以合并,于是我们就可以预处理简化指令。
例如:
1、先向右走2米,再向左走1米,再向右走2米。那么这三条指令就可以合并为向右走3米。
2、先向右走1米,再向右走1米。那么这两条指令可以合并为向右走2米。
需要注意合并前可达的区域合并后也必须全部可达。
这一题还有许多其他的剪枝方法。
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
using namespace std;
int n,m,k,t,opd[1005],ops[1005],cnt;
int dir[4][2]={1,0,0,1,-1,0,0,-1};//S E N W
char G[1005][1005],ans[30];
struct node
{
int y,x,step;
char st;
}p;
queue<node> q;
int getdir(char c)
{
if(c=='S') return 0;
if(c=='E') return 1;
if(c=='N') return 2;
if(c=='W') return 3;
}
void bfs()
{
while(!q.empty())
{
node top=q.front(); q.pop();
if(top.step==t)
{
ans[cnt++]=top.st;
continue;
}
int nextd=opd[top.step];
p.st=top.st;
p.step=top.step+1;
p.y=top.y+ops[top.step]*dir[nextd][0];
p.x=top.x+ops[top.step]*dir[nextd][1];
if(p.y<0 || p.y>=n || p.x<0 || p.x>=m) continue;
int i;
for(i=1;i<=ops[top.step];i++)
if(G[top.y+i*dir[nextd][0]][top.x+i*dir[nextd][1]]=='#') break;
if(i>ops[top.step]) q.push(p);
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
while(!q.empty()) q.pop();
char op[2];
t=0;
for(int i=0;i<n;i++)
scanf("%s",G[i]);
scanf("%d",&k);
for(int i=0;i<k;i++)
{
scanf("%s%d",op,&ops[t]);
opd[t]=getdir(op[0]);
if(t>=2 && opd[t]==opd[t-2] && opd[t-1]%2==opd[t-2]%2 && ops[t-1]<=ops[t-2] && ops[t-2]+ops[t]>=ops[t-1])
{
t-=2;
ops[t]=ops[t]-ops[t+1]+ops[t+2];
}
if(t && opd[t]==opd[t-1])
{
t--;
ops[t]=ops[t]+ops[t+1];
}
t++;
}
cnt=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(G[i][j]>='A' && G[i][j]<='Z')
{
p.st=G[i][j];
p.y=i;
p.x=j;
p.step=0;
q.push(p);
}
}
}
bfs();
sort(ans,ans+cnt);
ans[cnt]=0;
if(cnt) puts(ans);
else puts("no solution");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: