hdu1175 (BFS)

来源:互联网 发布:淘宝客服介入会成功吗 编辑:程序博客网 时间:2024/05/18 15:52

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

题意:一个连连看游戏让你判断两个点能不能消去。

总结:心态直接炸裂,改了三个小时各种wrong,我靠!!!!崩溃。思路:用bfs,bfs的时候要将不满足条件的去掉。网上好像dfs也可以。这个bfs需要储存每个节点的方向以及拐过次数。再进行筛选入队就可以了。

代码:

#include <iostream>#include <cstdio>#include <queue>using namespace std;int dir[4][2]={{1,0},{-1,0},{0,1},{0,-1}};int a[1010][1010],visit[1010][1010];//visit用来标记转折次数标记是否被访问过了int m,n;int i,j,k;struct node{    int x;int y;    int dir,countcorn;//dir方向,countcorn为拐角的次数};node start,End;void bfs(){    queue<node>Q;    while(!Q.empty())        Q.pop();    node next,now;    start.dir=-1,start.countcorn=0;Q.push(start);    while(!Q.empty()){        now=Q.front();        Q.pop();        if(now.x==End.x&&now.y==End.y){            printf("YES\n"); return ;        }        for(k=0;k<4;k++){            next.x=now.x+dir[k][0];            next.y=now.y+dir[k][1];            next.countcorn=now.countcorn;            next.dir=k;            if(now.dir!=next.dir&&now.dir!=-1) next.countcorn++;//如果不是起点且方向发生了变化++            if(next.x<1||next.y<1||next.x>n||next.y>m||next.countcorn>2) continue;//超出了限制或者拐弯数超过了2            if(a[next.x][next.y]&&!(next.x==End.x&&next.y==End.y)) continue;//如果相邻的是数字而不是空格。终点除外            /*if(!visit[next.x][next.y]){//这样写疯狂wa,简直无情                visit[next.x][next.y]=1;                Q.push(next);            }*/            if(next.countcorn<=visit[next.x][next.y]){//某些点可以重复经过,但是一定要拐角数小!!!!!!!!仍不是很明白,求高人指点                visit[next.x][next.y]=next.countcorn;                Q.push(next);            }        }    }    printf("NO\n");}int main(){    while(scanf("%d%d",&n,&m),n,m){        for(i=1;i<=n;i++)            for(j=1;j<=m;j++)            scanf("%d",&a[i][j]);        int T;scanf("%d",&T);        while(T--){            scanf("%d%d%d%d",&start.x,&start.y,&End.x,&End.y);            if(!a[start.x][start.y]||!a[End.x][End.y]||(a[start.x][start.y]!=a[End.x][End.y])){//在起始点不存在或者起始点不相同的时候都输出no                printf("NO\n");                continue;            }            for(i=1;i<=n;i++)                for(j=1;j<=m;j++)                    visit[i][j]=1e9;            bfs();        }    }    return 0;}


0 0
原创粉丝点击