标签:
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1728
之前没有做过类似这种要最少拐弯数的题目,一般求最少的用bfs应该比较好。。但是之前bfs一般都是用来求最小步数,也就可以标记过走过的点不再走。现在本题要的是最小的拐弯数,所以不能标记走过的点。。需要一个数组来记录当前这个点所需要的最小拐弯数,如果此时这个点的拐弯数比之前该点的拐弯数还小或者等于就更新这个值。遍历全图直到找到解为止。
学习:对于bfs找最优解的变形。明白如何更新拐弯数的,保证最小。
背景:1、WA对于保存拐弯数的数组没有初始化为无穷。2、MLE 对于每个点要进行拐弯数的判定,只有比之前保存的值还小或者等与才入队,否则队列会爆。。3、AC后还进行了一个剪枝,但是忘了将队列中的元素弹出。结果死循环。。。 下次注意最好将队列的头元素取出之后就弹出,避免忘记。。。
判定转弯数的时候一定要是等于号。。这是别人的题解http://972169909-qq-com.iteye.com/blog/1244218 看了图就明白了。。
代码:
//hdu 1728 #include<cstdio> #include<cstring> #include<queue> #define INF 10000000; using namespace std; int d1[4] = {0,0,1,-1}; int d2[4] = {1,-1,0,0}; int turn1[101][101]; char map[101][101]; int n,m,k; int ok; int sx,sy,ex,ey; struct state { int x,y; int turn; int dir; }cur,next1; void bfs(state temp) { temp.dir = -1; temp.turn = 0; turn1[temp.x][temp.y] = 0; queue<state> q; q.push(temp); while(!q.empty()) { cur = q.front(); q.pop(); //之后最好将队列的头元素取出之后就将其弹出,避免之后忘记。。不要像以前那样写在下面。。防止剪枝的时候出错。。 if(cur.x == ex-1 && cur.y == ey-1) { if(cur.turn <= k) { ok = 1; printf("yes\n"); return ; } } if(cur.turn > k) { //q.pop(); //剪枝后没有写这句然后死循环 continue; } for(int i = 0;i < 4;i++) { next1.x = cur.x + d1[i]; next1.y = cur.y + d2[i]; if(next1.x>=0&&next1.x<n&&next1.y>=0&&next1.y<m&&map[next1.x][next1.y]!='*') { if(cur.dir!=i &&cur.dir!=-1) { next1.dir = i; next1.turn = cur.turn+1; if(next1.turn<=turn1[next1.x][next1.y])//此处必须是等于号 { turn1[next1.x][next1.y] = next1.turn; q.push(next1); //一定要保证当前的转弯数是该点转弯数最小的才入队。。不然直接爆空间。。 } } else { next1.dir = i; next1.turn = cur.turn; if(next1.turn<=turn1[next1.x][next1.y]) { turn1[next1.x][next1.y] = next1.turn; q.push(next1); } } } } //q.pop(); } } int main () { int t; scanf("%d",&t); while(t--) { ok = 0; scanf("%d %d",&n,&m); for(int i = 0;i < n;i++) for(int j = 0;j < m;j++) turn1[i][j] = INF; for(int i = 0;i < n;i++) scanf("%s",map[i]); scanf("%d%d%d%d%d",&k,&sy,&sx,&ey,&ex); cur.x = sx-1; cur.y = sy-1; bfs(cur); if(!ok) printf("no\n"); } return 0; }
标签:
原文地址:http://blog.csdn.net/liujc_/article/details/44515969