HDU_2579_bfs
Posted 冷暖知不知
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HDU_2579_bfs相关的知识,希望对你有一定的参考价值。
http://acm.split.hdu.edu.cn/showproblem.php?pid=2579
简单bfs题,刚开始在纠结怎么存放vis,因为步数可能有几百步,这么多格子开数组的话也太多了,后来想到只要保存步数%k的状态就好了,bfs到达该点的步数肯定是最优的。
#include<iostream> #include<string> #include<cstring> #include<queue> using namespace std; string s[105]; int r,c,k,dir[4][2] = {-1,0,0,-1,1,0,0,1},vis[105][105][15],flag; struct point { int x,y,counts; }start; int main() { int n; cin >> n; while(n--) { flag = 0; memset(vis,0,sizeof(vis)); cin >> r >> c >> k; for(int i = 0;i < r;i++) cin >> s[i]; for(int i = 0;i < r;i++) { for(int j = 0;j < c;j++) { if(s[i][j] == ‘Y‘) { start.x = i; start.y = j; goto there; } } } there: start.counts = 0; queue<point> q; q.push(start); vis[start.x][start.y][0] = 1; while(!q.empty()) { int x = q.front().x,y = q.front().y,counts = q.front().counts; q.pop(); if(s[x][y] == ‘G‘) { flag = 1; cout << counts << endl; break; } for(int i = 0;i < 4;i++) { int xx = x+dir[i][0],yy = y+dir[i][1],z = (counts+1)%k; if(xx < 0 || xx >= r || yy < 0 || yy >= c) continue; if(s[xx][yy] == ‘#‘ && z) continue; if(vis[xx][yy][z]) continue; point temp; temp.x = xx; temp.y = yy; temp.counts = counts+1; q.push(temp); vis[xx][yy][z] = 1; } } if(!flag) cout << "Please give me another chance!" << endl; } return 0; }
以上是关于HDU_2579_bfs的主要内容,如果未能解决你的问题,请参考以下文章
HDU_1026_Ignatius and the Princess I_BFS(保存路径)
POJ2579 LA2858 HDU1218 Blurred Vision水题