poj 3083 dfs+bfs

来源:互联网 发布:神武2mac版能玩吗 编辑:程序博客网 时间:2024/05/20 04:13

背景:竟然G++,wa了一发,同样的代码,改为C++就过。。。后来看了discuss里面人说bfs最后虽然不会用到有return 的情况,也要加上,这个warning警告了的,没想到加上就ac了。。。

思路:bfs求最短路,然后就是对一直向左和一直向右进行dfs,方法是:记录上一次来的方向,然后根据上一次来的方向确定当前方向怎样才是向左,怎样才是向右,向左的话是顺时针转动,向右的话是逆时针转动。

我的代码:

#include <set>#include <stack>#include <queue>#include <vector>#include <cstdio>#include <cstring>#include <cstdlib>#include <iostream>#include <algorithm>#define LL long long intusing namespace std;const int M=42,INF=0x3fffffff;int n,m,dir[4][2]={0,-1,-1,0,0,1,1,0},ans;bool diagram[M][M],vis[M][M];struct place{int x,y,last_dir,step;}s,e,temp1,temp2;int bfs(void){    queue<place> q1;    s.step=0;    q1.push(s);    while(!q1.empty()){        temp1=q1.front();        q1.pop();        if(temp1.x == e.x && temp1.y == e.y) return temp1.step;        for(int j=0,i=temp1.last_dir-1;j < 4;j++,i++){            if(i == -1) i=3;            if(i == 4) i=0;            temp2.x=temp1.x+dir[i][0];            temp2.y=temp1.y+dir[i][1];            if(temp2.x > 0 && temp1.x > 0 && temp1.x <= n && temp1.x <= m && !vis[temp2.x][temp2.y] && diagram[temp2.x][temp2.y]){                temp2.last_dir=i;                temp2.step=temp1.step+1;                vis[temp2.x][temp2.y]=1;                q1.push(temp2);            }        }    }    return 0;}void dfs(place pla,int d){    if(ans >= 0) return;    if(pla.x == e.x && pla.y == e.y){ans=pla.step;return;}    int i;    if(d == 0) i=pla.last_dir-1;    else i=pla.last_dir+1;    for(int j=0;j < 4;j++){        if(i == -1) i=3;        if(i == 4) i=0;        if(pla.x+dir[i][0] > 0 && pla.y+dir[i][1] <= m && pla.x+dir[i][0] <= n && pla.y+dir[i][1] > 0 && diagram[pla.x+dir[i][0]][pla.y+dir[i][1]]){            pla.step++;            pla.last_dir=i;            pla.x+=dir[i][0];            pla.y+=dir[i][1];            dfs(pla,d);        }        if(!d) i++;        else i--;    }}int main(void){    int t;    scanf("%d",&t);    while(t--){        scanf("%d%d",&m,&n);        getchar();        for(int i=1;i <= n;i++){            for(int j=1;j <= m;j++){                char c;                scanf("%c",&c);                c == '#' ? diagram[i][j]=0 : diagram[i][j]=1;                if(c == 'S'){                    s.x=i,s.y=j;                    if(j == 1) s.last_dir=2;                    else if(j == m) s.last_dir=0;                    else if(i == 1) s.last_dir=3;                    else if(i == n) s.last_dir=1;                }                if(c == 'E') e.x=i,e.y=j;            }            getchar();        }        memset(vis,0,sizeof(vis));        int min_step=bfs()+1;        //cout << min_step << endl;        ans=-1;        dfs(s,0);//0代表一直左转        printf("%d ",ans+1);        ans=-1;        dfs(s,1);        printf("%d %d\n",ans+1,min_step);    }    return 0;}

0 0