洛谷P1443 马的遍历 //bfs求路径长度。
http://www.luogu.org/problem/show?pid=1443
bfs求路径长,裸bfs,水题一枚,我却调了二十分钟。
最后由于 dis[x1][y1]=dis[e.x][e.y]+1; 这句放错位置(放到了 if{ } 外面。。。)
这个题输出比较搞笑。。。记录一下数字位数即可。。
代码如下
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<string> 5 #include<cstring> 6 #include<queue> 7 #include<cstdlib> 8 #include<algorithm> 9 #define for1(i,n,m) for(int i=(n);i<=(m);i++) 10 #define for2(i,n,m) for(int i=(n);i>=(m);i--) 11 using namespace std; 12 int n,m,sx,sy; 13 int dis[205][205],f1[8]={1,1,-1,-1,2,2,-2,-2},f2[8]={2,-2,2,-2,1,-1,1,-1}; 14 bool v[205][205]; 15 struct node 16 { 17 int x,y; 18 }; 19 queue<node> q; 20 21 void bfs(int x,int y) 22 { 23 q.push({x,y}); 24 v[x][y]=1; 25 while(!q.empty()) 26 { 27 28 node e=q.front(); 29 q.pop(); 30 for1(i,0,7) 31 { 32 int x1=e.x+f1[i],y1=e.y+f2[i]; 33 if(!v[x1][y1]&&x1>0&&x1<=n&&y1>0&&y1<=m) 34 { 35 v[x1][y1]=1; 36 q.push({x1,y1}); 37 dis[x1][y1]=dis[e.x][e.y]+1; 38 } 39 //dis[x1][y1]=dis[e.x][e.y]+1; 原来这句话放到了这里。。。 40 } 41 } 42 } 43 44 int main() 45 { 46 cin>>n>>m>>sx>>sy; 47 bfs(sx,sy); 48 for1(i,1,n) 49 { 50 for1(j,1,m) 51 { 52 if(!v[i][j]) 53 cout<<"-1 "; 54 else 55 { 56 cout<<dis[i][j]; 57 if(!dis[i][j]) //如果dis是零下面数数字位数的过程出问题,拿出来考虑 58 cout<<" "; 59 else 60 { 61 62 int num=0,tmp=dis[i][j]; 63 while(tmp) 64 { 65 tmp/=10; 66 num++; 67 } //数数字位数 68 for1(i,1,5-num) 69 cout<<" "; 70 } 71 } 72 } 73 cout<<endl; 74 } 75 return 0; 76 }

浙公网安备 33010602011771号