初学搜索,刚开始没看清题,题上要求输入的两个坐标是先输入列后输入行,习惯性按行列输入,结果怎么都不对。
这道题少考虑的好多,一直WA,改了两个多小时,唉,头脑太简单了……
首先,这个题从起点可能有多条路能到达这个终点,所以要确定的是到这个终点的最小拐弯数,这是第一点要注意的
其次,这道题中不能对已走的点进行标记,因为可能有多条路径走这个点,如果标记了已走的点,就可能影响另外通向终点并且拐弯最小的路径不能到达终点
这里,我采用的方法是对方向flag进行标记,count表示到当前节点所转过的弯数,同向的即没有拐弯:count保持不变 否则count+1;
菜鸟在努力……
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<stdio.h> 2 #include<string.h> 3 #include<queue> 4 using namespace std; 5 struct node 6 { 7 int x,y; 8 int count; 9 int flag; 10 }; 11 int a[105][105]; 12 char map[105][105]; 13 int n,m; 14 int c,sx,sy,cx,cy; 15 int d[4][2]={0,1,0,-1,1,0,-1,0}; 16 int mark[4]={1,2,3,4}; 17 int judge(int x,int y) 18 { 19 if(x>=1&&x<=n&&y>=1&&y<=m&&map[x][y]!='*') 20 return 1; 21 return 0; 22 } 23 int bfs() 24 { 25 int i; 26 queue<node>q; 27 node cur,next; 28 cur.x=sx; 29 cur.y=sy; 30 cur.count=0; 31 cur.flag=0; 32 q.push(cur); 33 while(!q.empty()) 34 { 35 cur=q.front(); 36 q.pop(); 37 for(i=0;i<4;i++) 38 { 39 next.x=cur.x+d[i][0]; 40 next.y=cur.y+d[i][1]; 41 next.flag=i+1; 42 if(judge(next.x,next.y)) 43 { 44 if(cur.flag!=next.flag){next.count=cur.count+1;} 45 else{next.count=cur.count;} 46 47 if(next.count<=a[next.x][next.y]) 48 { 49 a[next.x][next.y]=next.count; 50 q.push(next); 51 } 52 } 53 } 54 } 55 return a[cx][cy]; 56 } 57 58 int main() 59 { 60 int t,i,j,k; 61 scanf("%d",&t); 62 while(t--) 63 { 64 scanf("%d%d",&n,&m); 65 for(i=1;i<=n;i++) 66 scanf("%s",map[i]+1); 67 scanf("%d%d%d%d%d",&c,&sy,&sx,&cy,&cx); 68 if(sy==cy&&sx==cx) 69 { 70 printf("yes "); 71 continue; 72 } 73 memset(a,9,sizeof(a)); 74 int ans; 75 ans=bfs()-1;//由于从第一个点向四个方向走,不能算拐弯,所以将多算的那次减去 76 if(ans>c) 77 printf("no "); 78 else 79 printf("yes "); 80 } 81 return 0; 82 }