题目: P1746 离开中山路
我的代码:
#include <bits/stdc++.h>
using namespace std;
int q1[10005];
int q2[10005];
int s[10005];
int x;
int m[10005][10005];
bool flag[10005][10005];
int a1,b1,a2,b2;
int t1=0,t2=0,w1=1,w2=1;
void bfs(){
while(1){
t1++;
t2++;
if(w1+1==t1) break;
int ss=s[t1];
int l1=q1[t1];
int l2=q2[t2];
if(l1==a2&&l2==b2){
cout<<ss;
break ;
}
int u=1;
if(flag[l1+1][l2]==false&&m[l1+1][l2]==0&&(l1+1)<=x){
q1[t1+u]=l1+1;
q2[t2+u]=l2;
s[t1+u]=ss+1;
m[l1+1][l2]=true;
w1++;
w2++;
u++;
}
if(flag[l1][l2+1]==false&&m[l1][l2+1]==0&&(l2+1)<=x){
q1[t1+u]=l1;
q2[t2+u]=l2+1;
s[t1+u]=ss+1;
m[l1][l2+1]=true;
w1++;
w2++;
u++;
}
if(flag[l1-1][l2]==false&&m[l1-1][l2]==0&&(l1-1)>0){
q1[t1+u]=l1-1;
q2[t2+u]=l2;
s[t1+u]=ss+1;
m[l1-1][l2]=true;
w1++;
w2++;
u++;
}
if(flag[l1][l2-1]==false&&m[l1][l2-1]==0&&(l2-1)>0){
q1[t1+u]=l1;
q2[t2+u]=l2-1;
s[t1+u]=ss+1;
m[l1][l2-1]=true;
w1++;
w2++;
u++;
}
}
}
int main(){
char o;
cin>>x;
for(int i=1;i<=x;i++){
for(int j=1;j<=x;j++){
cin>>o;
if(o=='0'){
m[i][j]=0;
}
else m[i][j]=1;
}
}
cin>>a1>>b1>>a2>>b2;
q1[1]=a1;
q2[1]=b1;
s[1]=0;
flag[a1][b1]=true;
bfs();
return 0;
}
测试结果:满江红