hdu 1175 连连看(bfs)

来源:互联网 发布:网络皮包公司 编辑:程序博客网 时间:2024/06/10 08:24

题意:

不从外面走的连连看。


解析:

抽象为图上一个点到另一个点,只能拐2次弯。

然后用bfs来每询问一次爆一个就行了。

入队条件是下一个点的拐弯次数小于当前的,或者下一个点没有被访问过。


代码:

#include <iostream>#include <cstdio>#include <cstdlib>#include <algorithm>#include <cstring>#include <cmath>#include <stack>#include <vector>#include <queue>#include <map>#define LL long long#define lson lo, mi, rt << 1#define rson mi + 1, hi, rt << 1 | 1using namespace std;const int maxn = 1000 + 10;const int inf = 0x3f3f3f3f;const double eps = 1e-6;const double pi = acos(-1.0);const double ee = exp(1.0);int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};int n, m;int g[maxn][maxn];int mark[maxn][maxn];struct Point{    int x, y, d;    Point(int _x, int _y, int _d)    {        x = _x;        y = _y;        d = _d;    }};bool bfs(int sx, int sy, int ex, int ey){    memset(mark, 0, sizeof(mark));    queue<Point> q;    q.push(Point(sx, sy, -1));    mark[sx][sy] = 0;    while (!q.empty())    {        Point now = q.front();        q.pop();        int x = now.x;        int y = now.y;        int d = now.d;        for (int i = 0; i < 4; i++)        {            int nx = x + dir[i][0];            int ny = y + dir[i][1];            int nd = i;            int cnt = 0;            if (nd != d)                cnt = mark[x][y] + 1;            else                cnt = mark[x][y];            if (0 <= nx && nx < n && 0 <= ny && ny < m)            {                if (cnt <= mark[nx][ny] || !mark[nx][ny])                {                    if (nx == ex && ny == ey && cnt <= 3)                    {                        return true;                    }                    if (g[nx][ny] == 0)                    {                        mark[nx][ny] = cnt;                        if (cnt >= 4)///剪枝                            continue;                        q.push(Point(nx, ny, i));                    }                }            }        }    }    return false;}int main(){#ifdef LOCAL    freopen("in.txt", "r", stdin);#endif // LOCAL    while (~scanf("%d%d", &n, &m))    {        if (!n && !m)            break;        for (int i = 0; i < n; i++)        {            for (int j = 0; j < m; j++)            {                scanf("%d", &g[i][j]);            }        }        int d;        scanf("%d", &d);        while (d--)        {            int sx, sy, ex, ey;            scanf("%d%d%d%d", &sx, &sy, &ex, &ey);            sx--, sy--, ex--, ey--;            if (g[sx][sy] != g[ex][ey] || g[sx][sy] == 0 || g[ex][ey] == 0)                printf("NO\n");            else if (bfs(sx, sy, ex, ey))                printf("YES\n");            else                printf("NO\n");        }    }    return 0;}


0 0