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; }
时间: 2024-10-16 21:57:01