【HDOJ 5335】Walk Out

【HDOJ 5335】Walk Out

DFS或者BFS 需要极大的剪枝叶否则必超
BFS做的 起点1的话正常搜 0的话从起点找离终点距离最近(x+y最大)的几个点放在队列中然后再搜
搜的时候也要剪枝 用一个变量存放当前搜到的点在最终结果中处在的位置 然后再比较与最近距离还有该点已匹配的字符(‘1’/’0’) 任何一项不优 continue 在注意些特判之类的 A的也挺累。。。

代码如下:

#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <queue>
#define INF 0x3f3f3f3f

using namespace std;

typedef struct Point
{
    int x,y,step;
}Point;


bool vis[1111][1111];
char str[1111111];
char mp[1111][1111];
int m,n;
int dirx[] = {-1, 0, 0, 1};
int diry[] = { 0,-1, 1, 0};
int dd[1111111];

bool in(int x,int y) { return (x > 0 && x <= m && y > 0 && y <= n);}

bool bfs()
{
    int d = 0,i,x,y,st,s;
    Point p;
    memset(vis,0,sizeof(vis));
    queue <Point> ls;
    queue <Point> q;
    if(mp[1][1] == '1') q.push(Point{1,1,0});
    else ls.push(Point{1,1,0});
    vis[1][1] = 1;
    while(!ls.empty())
    {
        p = ls.front();
        ls.pop();

        if(p.x == m && p.y == n) return true;
        for(i = 0; i < 4; ++i)
        {
            x = p.x + dirx[i];
            y = p.y + diry[i];
            if(!in(x,y) || vis[x][y]) continue;
            if(mp[x][y] == '1')
            {
                if(x+y > d)
                {
                    d = x+y;
                    while(!q.empty()) q.pop();
                }
                q.push(Point{x,y,0});
        //printf("%d %d\n",x,y);
            }
            else ls.push(Point{x,y,0});
            vis[x][y] = 1;
        }
    }
    memset(str,0,sizeof(str));
    str[0] = '1';
    memset(dd,0,sizeof(dd));
    s = 0;
    while(!q.empty())
    {
        p = q.front();
        q.pop();
        x = p.x;
        y = p.y;
        st = p.step;
        if(x == m && y == n && st == 0) return false;
        if(st != 0 && (mp[x][y] > str[st] || x+y < dd[st]) )continue;

        for(i = 0; i < 4; ++i)
        {
            x = p.x + dirx[i];
            y = p.y + diry[i];
            if(!in(x,y) || vis[x][y]) continue;

            if(!str[st+1] )
            {
                dd[st+1] = x+y;
                str[st+1] = mp[x][y];
            }
            else if(dd[st+1] < x+y)
            {
                dd[st+1] = x+y;
                str[st+1] = mp[x][y];
            }
            else if(x + y == dd[st+1]) str[st+1] = min(str[st+1],mp[x][y]);
            else continue;

            if(x == m && y == n) return false;

            q.push(Point{x,y,st+1});
            vis[x][y] = 1;
        }
    }
    return false;
}

int main()
{
    //freopen("in.in","r",stdin);
    //freopen("out.out","w",stdout);
    int t,i;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d %d",&m,&n);
        for(i = 1; i <= m; ++i)
            scanf("%s",mp[i]+1);
        if(bfs()) printf("0\n");
        else printf("%s\n",str);
    }
    return 0;
}

你可能感兴趣的:(bfs)