hdu 1728 逃離迷宮(廣搜 多路徑問題)

初學搜索,剛開始沒看清題,題上要求輸入的兩個座標是先輸入列後輸入行,習慣性按行列輸入,結果怎麼都不對。node

這道題少考慮的好多,一直WA,改了兩個多小時,唉,頭腦太簡單了……ide

首先,這個題從起點可能有多條路能到達這個終點,因此要肯定的是到這個終點的最小拐彎數,這是第一點要注意的spa

其次,這道題中不能對已走的點進行標記,由於可能有多條路徑走這個點,若是標記了已走的點,就可能影響另外通向終點而且拐彎最小的路徑不能到達終點code

這裏,我採用的方法是對方向flag進行標記,count表示到當前節點所轉過的彎數,同向的即沒有拐彎:count保持不變   不然count+1;blog

菜鳥在努力……string

 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\n");
71             continue;
72         }
73         memset(a,9,sizeof(a));
74         int ans;
75         ans=bfs()-1;//因爲從第一個點向四個方向走,不能算拐彎,因此將多算的那次減去
76         if(ans>c)
77             printf("no\n");
78         else
79             printf("yes\n");
80     }
81     return 0;
82 }
View Code
相關文章
相關標籤/搜索