HDU 1175 连连看 BFS

来源:互联网 发布:java 线程间共享变量 编辑:程序博客网 时间:2024/05/16 07:25

思路:我是用BFS去找的,这样就出现了一个问题,一个结点可能有n个结点依次访问这个结点,但如果用vis数组标记的话,访问一次就不能访问了,万一后面的访问得到的结果更好呢?于是我就脑补了一个想法,记录这个点被访问到的时候经历过的转折的最小值,如果后面的访问到这一步经历过的转折这个转折的最小值的话,就将这个点重新加入队列中。

坑点:就是如果=这一步的最小值也是要加入队列中的,因为方向不同,可能会得到更好的结果。(因为这个WA了一发,都是泪。)

数据:

3 4

5 0 0 1

5 1 0 0

0 0 0 5

4

3 4 1 1

1 1 3 4

2 1 3 4

3 4 2 1

0 0

输出:

YES

YES

YES

YES

http://acm.hdu.edu.cn/showproblem.php?pid=1175

/*********************************************    Problem : HDU 1175    Author  : NMfloat    InkTime (c) NM . All Rights Reserved .********************************************/#include <map>#include <set>#include <queue>#include <cmath>#include <ctime>#include <cstdio>#include <cstring>#include <cstdlib>#include <iostream>#include <algorithm>#define rep(i,a,b)  for(int i = (a) ; i <= (b) ; i ++)#define rrep(i,a,b) for(int i = (b) ; i >= (a) ; i --)#define repE(p,u) for(Edge * p = G[u].first ; p ; p = p -> next)#define cls(a,x)   memset(a,x,sizeof(a))#define eps 1e-8using namespace std;const int MOD = 1e9+7;const int INF = 0x3f3f3f3f;const int MAXN = 1e5+5;const int MAXE = 2e5+5;typedef long long LL;typedef unsigned long long ULL;int T,n,m,k;int Map[1005][1005];int Mapz[1005][1005];int x11,y11,x22,y22;int fx[] = {0,1,-1,0,0} ;int fy[] = {0,0,0,1,-1} ;struct Node {    int x,y;//坐标;    int z;//经过了多少次转折。    int fa; //到达Node的方向    Node(){}    Node(int _x, int _y,int _z,int _fa){x = _x ; y = _y;z = _z;fa = _fa;}};queue<Node>q;int ok;void BFS() {    while(!q.empty())q.pop();    q.push(Node(x11,y11,0,0));    while(!q.empty()) {        Node tmp = q.front();        q.pop();        if(tmp.z > 3) continue;        if(tmp.x == x22 && tmp.y == y22) { ok = 1 ; break ; }        int tmpx,tmpy,zhe;        rep(i,1,4) {            tmpx = tmp.x + fx[i] ;             tmpy = tmp.y + fy[i] ;            if(tmpx >= 1 && tmpx <= n && tmpy >= 1 && tmpy <= m) {                if(Map[tmpx][tmpy] == 0 || (tmpx == x22 && tmpy == y22)) {                    zhe = tmp.z;                    if(i != tmp.fa) zhe ++;                    if(Mapz[tmpx][tmpy] >= zhe) {                        Mapz[tmpx][tmpy] = zhe;                        q.push(Node(tmpx,tmpy,zhe,i));                    }                }            }        }    }}void input() {    rep(i,1,n) rep(j,1,m) scanf("%d",&Map[i][j]);}void solve() {    int q;    scanf("%d",&q);    rep(i,1,q) {        ok = 0;        scanf("%d %d %d %d",&x11,&y11,&x22,&y22);        if((Map[x11][y11] == Map[x22][y22]) && (Map[x11][y11] != 0))         {            cls(Mapz,0x3f);            Mapz[x11][y11] = 0;            BFS();        }        if(x11 == x22 && y11 == y22) ok = 0;        if(ok) puts("YES");        else puts("NO");    }}int main(void) {    //freopen("a.in","r",stdin);    //scanf("%d",&T); while(T--) {    while(scanf("%d %d",&n,&m),n+m) {    //while(scanf("%d",&n),n) {        input();        solve();    }    return 0;}
0 0
原创粉丝点击