https://www.acwing.com/problem/content/846/
重大问题 以后tmpa a 不要搞混
#include<bits/stdc++.h>
using namespace std;
const int N=1000;
int n,m;
int _m[N][N];
bool _book[N][N];
int _path[N][N];
struct P {
int x;
int y;
int s;
} que[N*N];
bool flag=false;
int _next[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
void bfs() {
int hh=0, tt=0;
int a, b;
int tmpa, tmpb;
_book[0][0]=true;
while(hh<=tt) {
a=que[hh].x;
b=que[hh].y;
for(int i=0; i<4; i++) {
tmpa=a+_next[i][0];
tmpb=b+_next[i][1];
if(a<0||b<0||a>=n||b>=m) continue; //这里还是没改
if(!_m[tmpa][tmpb]&&!_book[tmpa][tmpb]) {
_book[tmpa][tmpb]=true;
tt++;
que[tt].x=tmpa;
que[tt].y=tmpb;
que[tt].s=que[hh].s+1;
_path[tmpa][tmpb]=que[tt].s;
}
if(tmpa==n-1&&tmpb==m-1) {
flag=true;
break;
}
}
hh++;
if(flag) break;
}
cout<<que[tt].s<<endl;
// for(int i=0;i<n;i++) {
// for(int j=0;j<m;j++) {
// if(_m[i][j]) cout<<" ";
// else cout<<_path[i][j]<<" ";
//
// }
// cout<<"\n";
// }
// cout<<"\n";
return ;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>n>>m;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin>>_m[i][j];
bfs();
return 0;
}
/*
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
*/
#include<bits/stdc++.h>
using namespace std;
const int N=1000;
int n,m;
int _m[N][N];
bool _book[N][N];
int _path[N][N];
struct P {
int x;
int y;
int s;
} que[N*N];
bool flag=false;
int _next[4][2]= {{1,0},{0,1},{-1,0},{0,-1}};
void bfs() {
// for(int i=0; i<25; i++) {
// for(int j=0; j<25; j++)
// cout<<_m[i][j]<<" ";
// cout<<"\n";
// }
// cout<<"\n";
int hh=0, tt=0;
int a, b;
int tmpa, tmpb;
_book[0][0]=true;
while(hh<=tt) {
a=que[hh].x;
b=que[hh].y;
for(int i=0; i<4; i++) {
tmpa=a+_next[i][0];
tmpb=b+_next[i][1];
if(tmpa<0||tmpb<0||tmpa>=n||tmpb>=m) continue;
if(_m[tmpa][tmpb]&&!_book[tmpa][tmpb]) {
_book[tmpa][tmpb]=true;
tt++;
que[tt].x=tmpa;
que[tt].y=tmpb;
que[tt].s=que[hh].s+1;
_path[tmpa][tmpb]=que[tt].s;
if(tmpa==n-1&&tmpb==m-1) {
flag=true;
break;
}
}
}
if(flag) break;
hh++;
}
// printf("tt = %d\n",tt);
cout<<que[tt].s<<endl;
// for(int i=0;i<=tt;i++) printf("que[%d]: %d %d s = %d\n",i,que[i].x,que[i].y,que[i].s);
//
// for(int i=0; i<n; i++) {
// for(int j=0; j<m; j++)
// if(!_m[i][j]) cout<<" ";
// else cout<<_path[i][j]<<" ";
// cout<<"\n";
// }
// cout<<"\n";
return ;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
cin>>n>>m;
int t;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++) {
cin>>t;
if(!t) _m[i][j]=1;
}
bfs();
return 0;
}
/*
5 5
0 1 0 0 0
0 1 0 1 0
0 0 0 0 0
0 1 1 1 0
0 0 0 1 0
20 20
0 0 0 0 1 0 0 1 0 0 0 1 1 0 1 1 0 0 0 0
0 1 1 0 1 0 0 1 0 1 0 0 0 0 1 1 0 1 1 1
1 0 1 0 1 1 0 0 0 0 1 0 0 1 0 0 1 1 0 0
0 0 0 0 1 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0
0 1 0 1 0 0 0 1 0 0 0 1 0 0 1 0 0 0 1 1
1 0 0 0 0 1 0 0 0 0 0 1 0 1 0 0 0 1 0 0
1 0 1 1 0 1 0 0 1 1 1 0 1 0 0 1 0 1 0 0
0 0 0 0 0 1 1 0 0 0 1 1 0 1 1 0 0 0 0 0
0 0 0 0 1 1 0 0 0 0 0 0 1 0 0 0 1 0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