stud-2779裸bfs

c++的數組下標爲負數竟然不報錯

#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
#define DEBUG
const int maxn=15+5;
char buf[maxn][maxn];
bool visited[maxn][maxn];
int md[4][2]={0,1,0,-1,-1,0,1,0};
int m,n;
struct node
{
    int x,y,step;
    node(int x,int y,int step):x(x),y(y),step(step){}
};
void bfs(int x,int y,int t){
    queue<node> q;
    node u(x,y,0);
    memset(visited,0,sizeof(visited));
    visited[x][y]=1;
    q.push(u);
    while(!q.empty()){
        node u=q.front();q.pop();
        visited[u.x][u.y]=1;
        for(int i=0;i<4;i++){
            node temp(u.x+md[i][0],u.y+md[i][1],u.step+1);
            if(temp.x<0||temp.x>=m||temp.y<0||temp.y>=n)continue;
            if(visited[temp.x][temp.y]){continue;}

            if(buf[temp.x][temp.y]=='*'){q.push(temp);visited[temp.x][temp.y]=1;}
            else if(buf[temp.x][temp.y]=='Y'){printf("%d\n",temp.step);return;}
            else{
                cout<<temp.x<<"\t"<<temp.y<<"\t"<<temp.step<<endl;
            }
        }
        u=q.front();
    }
    printf("%d\n",-1);

    // for(int i=0;i<4;i++){
    //  bfs(x+md[i][0],y+md[i][1],t);
    // }
}
void solve(){
    int sx,sy,ex,ey;
    for(int i=0;i<m;i++)
        for(int j=0;j<n;j++)
            if(buf[i][j]=='X')
                sx=i,sy=j;
            else if(buf[i][j]=='Y')
                ex=i,ey=j;
    bfs(sx,sy,0);
}
int main(){
#ifdef DEBUG
    freopen("in.txt", "r", stdin);
    freopen("out.txt", "w", stdout);
#endif
    while(scanf("%d%d",&m,&n)==2&&m&&n){
        for(int i=0;i<m;i++)scanf("%s",buf[i]);
        solve();
    }
#ifdef DEBUG
    fclose(stdin);
    fclose(stdout);
#endif
    return 0;
}
發佈了51 篇原創文章 · 獲贊 1 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章