Hoj 1030 Labyrinth
来源:互联网 发布:mysql网络编程 编辑:程序博客网 时间:2024/06/04 20:04
本题是经典的两次BFS题目。
题目链接:http://acm.hit.edu.cn/hoj/problem/view?id=1030
要求在图中找出距离最远的两个点的距离。
这题暴力枚举每一点出发的最长路径显然不可行。
从任意点A出发的最长路径的另一个端点称为B,那么B就是全局最长路径的一个端点。那么,从B点开始一次广搜,到达的最远点叫C。BC即是图中的最长路径。
证明参考:http://blog.csdn.net/nvfumayx/article/details/7540465
#include <iostream>#include <math.h>#include <stdio.h>#include <string.h>#include <queue>#include <algorithm>#include <stack>using namespace std;int column,row;int map[1002][1002];int dis[1002][1002];int disx[4] = {0,1,0,-1};int disy[4] = {1,0,-1,0};int maxX;int maxY;struct Point{ int x; int y;};int bfs(int startx,int starty){ queue<Point> p; Point nex,temp; maxX = startx; maxY = starty; int maxP = 0; nex.x = startx; nex.y = starty; p.push(nex); while(!p.empty()) { temp = p.front(); p.pop(); for(int i=0; i<4; i++) { int tempx = temp.x + disx[i]; int tempy = temp.y + disy[i]; if(tempx>=0 && tempx<row && tempy>=0 && tempy<column) { if(map[tempx][tempy] == 1) { map[tempx][tempy] = 2; dis[tempx][tempy] += dis[temp.x][temp.y] + 1; nex.x = tempx; nex.y = tempy; p.push(nex); if(dis[tempx][tempy]>maxP) { maxP = dis[tempx][tempy]; maxX = tempx; maxY = tempy; } } } } } return maxP;}int main(){#ifndef ONLINE_JUDGE freopen("in.txt","r",stdin);#endif int t; char c; scanf(" %d ",&t); int startx,starty; while(t--) { memset(map,0,sizeof(map)); memset(dis,0,sizeof(dis)); scanf(" %d %d ",&column,&row); for(int i=0; i<row; i++) { for(int j=0; j<column; j++) { scanf(" %c ",&c); if(c == '.') { map[i][j] = 1; } } } for(int i=0; i<row; i++) { int flag = 0; for(int j=0; j<column; j++) { if(map[i][j] == 1) { flag = 1; startx = i; starty = j; break; } } if(flag == 1) { break; } } map[startx][starty] = 2;//标记为已访问过 bfs(startx,starty); //还原原map for(int i=0; i<row; i++) { for(int j=0; j<column; j++) { if(map[i][j] == 2) { map[i][j] = 1; } } } memset(dis,0,sizeof(dis)); printf("Maximum rope length is %d.\n",bfs(maxX,maxY)); } return 0;}
- Hoj 1030 Labyrinth
- 【hoj】1030 Labyrinth
- (简单)搜索 HOJ 1030 Labyrinth
- HOJ 1030 Labyrinth----------------两次BFS求树的直径(图的最长路)
- Labyrinth
- Labyrinth
- Labyrinth
- Labyrinth
- HOJ 1030 && POJ 1383
- HOJ
- ZOJ1536 Labyrinth
- 1033. Labyrinth
- poj1383 - Labyrinth
- hdu4791 Labyrinth
- poj1383:Labyrinth
- HDU | Labyrinth
- 【POJ1383】Labyrinth
- poj-【Labyrinth】
- 游戏开发源代码收集
- Dojo Query 简介
- PLSQL 增加新库 tnsnames.ora
- 深入探讨MFC消息循环和消息泵 .
- 图像平滑、滤波、模糊
- Hoj 1030 Labyrinth
- 小技巧:打造个性化U盘图标
- python获取汉字的拼音
- C# Thread类的应用
- MetaData Service (MDS) in OA Framework
- 软件使用配置及连接
- Bacon's Cipher hdu4144 水题
- 魏永明谈“自主”操作系统
- HDFS文件操作命令