SJTU OJ 3008 Maze

SJTU OJ 3008 Maze

原题链接

第一次写关于bfs遍历图的题目,整理一下。
用队列存储可行的结点,pass[][]存储是否走过。
我的代码如下:

#include 
#include 
#include 
using namespace std;
int n, m, x1, y1, x2, y2;
char arr[105][105];
bool pass[105][105] = {false};
int xx[4]={1,0,0,-1};//下、右、左、上
int yy[4]={0,1,-1,0};
int re = -1;
struct node{
    int x;
    int y;
    int len;
};
queue q;
void bfs(){
    node s;
    s.x = x1;
    s.y = y1;
    s.len = 0;
    q.push(s);
    pass[x1][y1] = true;
    while(!q.empty())
    {
        node now=q.front();
        q.pop();
        for(int i=0;i<4;++i)
        {
            if (i==0 || i==3){
                if (arr[now.x][now.y] == '-') continue;
            }
            if (i==1 || i==2){
                if (arr[now.x][now.y] == '|') continue;
            }
            node New;
            New.x = now.x+xx[i];
            New.y = now.y+yy[i];
            New.len = now.len+1;
            if(New.x<1||New.y<1||New.x>n||New.y>m||pass[New.x][New.y]||arr[New.x][New.y]=='*')
                continue;
            if (i==0 || i==3){
                if (arr[New.x][New.y]=='-') continue;
            }
            if (i==1 || i==2){
                if (arr[New.x][New.y]=='|') continue;
            }
            q.push(New);
            pass[New.x][New.y] = true;
            if(New.x==x2 && New.y==y2){
                re = New.len;
                return;
            }
        }
    }
    return;
}
int main(){
    cin >> n >> m >> x1 >> y1 >> x2 >> y2;
    char tmp;
    for (int i=1; i<=n; i++){
        for (int j=1; j<=m; j++){
            cin >> arr[i][j];
        }
    }
    bfs();
    cout << re << endl;
    return 0;
}

你可能感兴趣的:(SJTUOJ,SJTUOJ,C++,算法题)