百练+BFS+图上visit标记嘛,因为是最短嘛,防止重复嘛

来源:互联网 发布:js正则判断数字范围 编辑:程序博客网 时间:2024/06/06 00:24
点击打开链接
#include<stdio.h>#include<stdlib.h>#include<iostream>#include<string.h>#include<cstring>#include<string>#include<algorithm>#include<math.h>#include<queue>#include<set>#define LL long long#define inf 0x3f3f3f3f#define mod 1e9+7const int maxn=205;using namespace std;int T,R,C,xx,yy;char Arr[maxn][maxn];bool vis[maxn][maxn];///标记使用bool型省空间int Move[4][2]={{-1,0},{1,0},{0,-1},{0,1}};struct Node{  int x,y,steps;};queue<Node>Q;void Search(){    for(int i=0; i<R; i++){        for(int j=0; j<C; j++){            if(Arr[i][j]=='S'){                xx=i;yy=j;                return;            }        }    }}void BFS(){    while(!Q.empty()) Q.pop();    memset(vis,0,sizeof(0));    Node temp1,temp2;    temp1.x=xx,temp1.y=yy;temp1.steps=0;    vis[xx][yy]=1;///为什么能标记,因为求最短步数,这个走过的一定不会走的。    Q.push(temp1);    while(!Q.empty()){        temp1=Q.front();Q.pop();        if(Arr[temp1.x][temp1.y]=='E'){            printf("%d\n",temp1.steps);        }        for(int i=0;i<4;i++){            temp2=temp1;            temp2.x+=Move[i][0];temp2.y+=Move[i][1];            if(temp2.x>=0&&temp2.x<R&&temp2.y>=0&&temp2.y<C&&!vis[temp2.x][temp2.y]&&Arr[temp2.x][temp2.y]!='#'){                temp2.steps+=1;                vis[temp2.x][temp2.y]=1;                Q.push(temp2);            }        }    }    printf("oop!\n");}int main(){    int i=0,j=0;    scanf("%d",&T);    while(T--){        scanf("%d %d",&R,&C);        for(i=0;i<R;i++)scanf("%s",Arr[i]);        Search();        BFS();    }    return 0;}

0 0
原创粉丝点击