P1979 [NOIP]华容道(70分的暴力)

来源:互联网 发布:淘宝数据魔方下载 编辑:程序博客网 时间:2024/04/30 15:39

https://www.luogu.org/problem/show?pid=1979
用裸的bfs写到了70分。
记录状态可以记录当前指定棋子的位置和空白格子的位置,还有一个步数(用结构体最好啦)。
直到指定棋子的位置到了目标格子时,就可以停止了。要注意空白格子可能与指定棋子换位置。

70分的暴力代码

#include<iostream>#include<cstring>#include<string>#include<algorithm>#include<cstdio>#include<queue>using namespace std;int n,m,q;int a[35][35];struct H{    int x,y,ex,ey,step;//当前位置  空白格子 };bool f[35][35][35][35];int dx[]={0,1,-1,0,0},dy[]={0,0,0,-1,1}; int bfs(int ex,int ey,int sx,int sy,int tx,int ty){    queue <H> q;    H l;l.x=sx,l.y=sy,l.ex=ex,l.ey=ey,l.step=0;    q.push(l);    f[sx][sy][ex][ey]=1;    while(!q.empty())    {        H k=q.front();q.pop();H l;        for(int i=1;i<=4;i++)        {            if(k.ex+dx[i]>=1&&k.ex+dx[i]<=n&&k.ey+dy[i]>=1&&k.ey+dy[i]<=m)            if(a[k.ex+dx[i]][k.ey+dy[i]])            {                H l=k;                if(k.ex+dx[i]==k.x&&k.ey+dy[i]==k.y) l.x=k.ex,l.y=k.ey;                l.ex=k.ex+dx[i],l.ey=k.ey+dy[i];                 if(!f[l.x][l.y][l.ex][l.ey]) l.step=k.step+1,q.push(l),f[l.x][l.y][l.ex][l.ey]=1;                if(l.x==tx&&l.y==ty) return l.step;            }        }    }    return -1;}int main(){    scanf("%d%d%d",&n,&m,&q);    for(int i=1;i<=n;i++) for(int j=1;j<=m;j++) scanf("%d",&a[i][j]);    while(q--)    {        memset(f,0,sizeof(f));        int ex,ey,sx,sy,tx,ty,ans;        scanf("%d%d%d%d%d%d",&ex,&ey,&sx,&sy,&tx,&ty);        if(sx==tx&&sy==ty) {printf("0\n");continue;}        ans=bfs(ex,ey,sx,sy,tx,ty);        printf("%d\n",ans);    }    return 0;} 

不要把暴力想象的太麻烦,只要想写,慢慢就可以写出来,不要畏难。