hihoCoder 1092 : Have Lunch Together
生活随笔
收集整理的這篇文章主要介紹了
hihoCoder 1092 : Have Lunch Together
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目大意:小hi和小ho去咖啡廳喝咖啡,咖啡廳可以看作是n * m的矩陣,每個點要么為空,要么被人、障礙物、椅子所占據,小hi和小ho想要找兩個相鄰的椅子。起初兩個人都在同一個點,求兩人到達滿足要求的椅子所移動的最少步驟。
思路:先BFS找出每個S到達每個椅子的最短路徑長度,然后遍歷每一行和每一列找出最優解。
代碼:
#include<cstdio> #include<cstring> #include<queue> #include<map> #include<cstdlib> #define INF 100000000 using namespace std;int n,m,d[10010],dir[4][2] = {-1,0,1,0,0,-1,0,1}; bool vis[10010]; char ch[110][110]; queue<int>Q;void bfs(int sx,int sy){int i,j,k;for(i=0;i<n;i++)for(j=0;j<m;j++){k = i*m + j;vis[k] = false;d[k] = INF; }k = sx * m + sy ; d[k] = 0;while(!Q.empty())Q.pop();Q.push(k);while(!Q.empty()){int x = Q.front();int tx = x/m ;int ty = x%m ; Q.pop();if(vis[x])continue;vis[x] = true;for(i=0;i<4;i++){int ex = tx + dir[i][0];int ey = ty + dir[i][1];if(ex<0 || ex>=n || ey<0 || ey>=m || ch[ex][ey] == '#' || ch[ex][ey] == 'P')continue;k = ex*m + ey;if(vis[k])continue;if(ch[ex][ey] == 'S'){d[k] = d[k] < d[x] + 1 ? d[k] : d[x] + 1;continue;}d[k] = d[k] < d[x] + 1 ? d[k] : d[x] + 1;Q.push(k);}} }int main(){int i,j,p1,p2,ans,sx,sy;bool tag;while(scanf("%d%d",&n,&m) == 2){ans = INF;bool flag = false;for(i=0;i<n;i++)scanf("%s",ch[i]);for(i=0;i<n && !flag;i++)for(j=0;j<m && !flag;j++)if(ch[i][j] == 'H'){sx = i;sy = j;flag = true;}bfs(sx,sy);int t1,t2;for(i=0;i<n;i++){p1 = p2 = INF ;for(j=0;j<m;j++){if(ch[i][j] == 'S'){int temp = d[i*m+j];if(p1 == INF)p1 = temp;else if(p2 == INF){p2 = temp;ans = ans < p1 + p2 ? ans : p1 + p2 ;p1 = p2;p2 = INF ;}}else if(ch[i][j] == 'P' || ch[i][j] == '#' || ch[i][j] == '.'){p1 = INF ;p2 = INF ;}}}for(j=0;j<m;j++){p1 = p2 = INF ;for(i=0;i<n;i++){if(ch[i][j] == 'S'){int temp = d[i*m+j];if(p1 == INF)p1 = temp;else if(p2 == INF){p2 = temp;ans = ans < p1 + p2 ? ans : p1 + p2 ;p1 = p2;p2 = INF ;}}else if(ch[i][j] == 'P' || ch[i][j] == '#' || ch[i][j] == '.'){p1 = INF ;p2 = INF ;}}}if(ans < INF)printf("%d\n",ans);elseprintf("Hi and Ho will not have lunch.\n");}return 0; }轉載于:https://www.cnblogs.com/jxgapyw/p/4845348.html
總結
以上是生活随笔為你收集整理的hihoCoder 1092 : Have Lunch Together的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: VIJOS1212 Way Select
- 下一篇: SGU185 Two shortest(