Fruit_candy @ 2023-05-23 21:03:50
#include<bits/stdc++.h>
using namespace std;
int n,a[1010][1010],x1,x2,y3,y2;
int dir[4][2]={{-1,0},{1,0},{0,1},{0,-1}};
struct node{
int x;
int y;
int step;
};
queue<node> q;
void bfs(){
while(!q.empty()){
node u=q.front();
if(u.x==x2&&u.y==y2){
cout<<u.step;
return;
}
for(int i=0;i<4;i++){
int xx=dir[i][0]+u.x;
int yy=dir[i][1]+u.y;
if(a[xx][yy]==0&&xx<=n&&xx>=1&&yy>=1&&yy<=n){
a[xx][yy]==1;
node e;
e.x=xx;
e.y=yy;
e.step=u.step+1;
q.push(e);
}
}
q.pop();
}
}
int main(){
ios::sync_with_stdio(false);
cin.tie(NULL);cout.tie(NULL);
cin>>n;
char xa;
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin>>xa;
a[i][j]=xa-'0';
}
}
cin>>x1>>y3>>x2>>y2;
node g;
g.x=x1;
g.y=y3;
g.step=0;
q.push(g);
bfs();
return 0;
}
只对了第二个,其他都MLE
by Jasonde1024 @ 2023-07-14 20:33:37
@Fruit_candy 真巧,我也是[捂脸]
by Jasonde1024 @ 2023-07-14 20:37:12
我现在调好了,你应该加一个used数组标记之前走过的路,防止重复。我这么做就AC了
by Jasonde1024 @ 2023-07-14 20:38:12
for (int i = 0; i < 4; ++i) {
int newx = x+dx[i];
int newy = y+dy[i];
if (newx > 0 && newx <= n && newy > 0 && newy <= n) {
if (used[newx][newy]) continue;
if (map[newx][newy] == '0') {
q.push(newx);
q.push(newy);
q.push(r+1);
used[newx][newy] = 1;
}
}
}