Wang Xifeng's Little Plot
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/65536 K (Java/Others)Total Submission(s): 71 Accepted Submission(s): 49
In the novel, Wang Xifeng was in charge of Da Guan Yuan, where people of Jia family lived. It was mentioned in the newly recovered pages that Wang Xifeng used to arrange rooms for Jia Baoyu, Lin Daiyu, Xue Baochai and other teenagers. Because Jia Baoyu was the most important inheritor of Jia family, and Xue Baochai was beautiful and very capable , Wang Xifeng didn't want Jia Baoyu to marry Xue Baochai, in case that Xue Baochai might take her place. So, Wang Xifeng wanted Baoyu's room and Baochai's room to be located at two ends of a road, and this road should be as long as possible. But Baoyu was very bad at directions, and he demanded that there could be at most one turn along the road from his room to Baochai's room, and if there was a turn, that turn must be ninety degree. There is a map of Da Guan Yuan in the novel, and redists (In China English, one whose job is studying 《Dream of the Red Chamber》is call a "redist") are always arguing about the location of Baoyu's room and Baochai's room. Now you can solve this big problem and then become a great redist.
There are several test cases.
For each case, the first line is an integer N(0<N<=100) ,meaning the map is a N × N matrix.
Then the N × N matrix follows.
The input ends with N = 0.
3 #.# ##. ..# 3 ... ##. ..# 3 ... ### ..# 3 ... ##. ... 0
3 4 3 5
题目大意:
在一个n*n的平面上'#'表示障碍物,'.'表示道路。
问,是否存在一点到另一点的路径的最长距离n。
这条路径满足,每个点可以朝8个方向前进,至多拐弯一次,而且只能拐90度的。
解析:记忆化搜索,对于每个'.'节点,搜索8个方向,记录下该方向,最远的距离,最后遍历每个'.'节点,求出所有节点所有90度的值最大值。最大值-1 就是最终结果(因为两段的起点被重复计算了一遍)。
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 105;
const int INF = 0x3f3f3f3f;
const int dr[] = {-1,-1,-1, 0, 1, 1, 1, 0};
const int dc[] = {-1, 0, 1, 1, 1, 0,-1,-1};
struct Node {
int step[8]; //记忆化搜索8个方向
}p[N][N];
char grid[N][N];
int n;
void solve(int r,int c) {
int x,y;
for(int d = 0; d < 8; d++) {
x = r;
y = c;
while(x >= 0 && x < n && y >= 0 && y < n && grid[x][y] != '#') {
p[r][c].step[d]++;
x += dr[d];
y += dc[d];
}
}
}
int main() {
while(scanf("%d",&n) != EOF && n) {
memset(p,0,sizeof(p));
for(int i = 0; i < n; i++) {
scanf("%s",grid[i]);
}
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '#') {
continue;
}
solve(i,j);
}
}
int maxn = -INF;
int sum,d;
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if(grid[i][j] == '#') {
continue;
}
for(int k = 0; k < 8; k++) {
d = (k+6) % 8; //当前方向左边
sum = p[i][j].step[k] + p[i][j].step[d];
maxn = max(maxn,sum);
d = (k+2) % 8; //当前方向右边
sum = p[i][j].step[k] + p[i][j].step[d];
maxn = max(maxn,sum);
}
}
}
printf("%d\n",maxn-1);
}
return 0;
}
175



被折叠的 条评论
为什么被折叠?



