/*
* poj1101.cpp
*
* Created on: 2010-8-13
* Author: friendy
*///
//这道题目好我的时间很长,但是发现了我的一个很大的错误。
//guang搜写的不行,主要是不知道为什么不让我用stl了
//
#include
#include
#include
#include
using namespace std;
int pos[4][2]={{-1, 0}, {0, 1}, {1, 0}, {0, -1}};
int maps[80][80], used[80][80];
int w, h;
struct Point {
int x, y;//zuobiao
int snum;//线段数
int d;//方向
} points[100000],tmp;
int x1, y1, x2, y2;
int ok(int i, int j) {//判断是否合法
if (i < 0 || j < 0 || i > h + 1 || j > w + 1)
return 0;
else
return 1;
}
int bfs() {
int i, x , y , t = -1, s = -1;
for (i = 0; i < 4; i++) {//更新第一个点的周围
x = x1 + pos[i][0];
y = y1 + pos[i][1];
while (ok(x, y)) {
if (x == x2 && y == y2)
return 1;
if (maps[x][y] != 1) {
t++;
used[x][y] = 1;
points[t].x = x;
points[t].y = y;
points[t].snum = 1;
points[t].d = i;
} else
break;
x += pos[i][0];
y += pos[i][1];
}
}
while (s != t) {//广搜
++s;
tmp.d = (points[s].d + 1) % 4;
tmp.x = points[s].x;
tmp.y = points[s].y;
tmp.snum = points[s].snum;
x = tmp.x + pos[tmp.d][0];
y = tmp.y + pos[tmp.d][1];
while (ok(x, y)) {
if (x == x2 && y == y2)
return tmp.snum + 1;
if (maps[x][y] == 1)
break;
if (used[x][y] == 0) {
t++;
used[x][y] = 1;
points[t].x = x;
points[t].y = y;
points[t].snum = tmp.snum + 1;
points[t].d = tmp.d;
} else
break;
x += pos[tmp.d][0];
y += pos[tmp.d][1];
}
tmp.d = (points[s].d + 3) % 4;
tmp.x = points[s].x;
tmp.y = points[s].y;
tmp.snum = points[s].snum;
x = tmp.x + pos[tmp.d][0];
y = tmp.y + pos[tmp.d][1];
while (ok(x, y)) {
if (x == x2 && y == y2)
return tmp.snum + 1;
if (maps[x][y] == 1)
break;
if (used[x][y] == 0) {
t++;
used[x][y] = 1;
points[t].x = x;
points[t].y = y;
points[t].snum = tmp.snum + 1;
points[t].d = tmp.d;
} else
break;
x += pos[tmp.d][0];
y += pos[tmp.d][1];
}
}
return -1;
}
int main() {
int i, j, cnt = 0;
char ch;
while (scanf("%d%d", &w, &h), w | h) {
cnt++;
getchar();
memset(maps, 0, sizeof(maps));
//memset(used, 0, sizeof(used));
for (i = 1; i <= h; i++) {
for (j = 1; j <= w; j++) {
ch = getchar();
if (ch == 'X')
maps[i][j] = 1;
}
getchar();
}
printf("Board #%d:/n", cnt);
int num = 0;
while (1) {
memset(used,0,sizeof(used));//非常容易忘
num++;
scanf("%d%d%d%d", &y1, &x1, &y2, &x2);
if (!(x1 | y1 | x2 | y2))
break;
int tt=bfs();
if (tt == -1)
printf("Pair %d: impossible./n", num);
else
printf("Pair %d: %d segments./n", num, tt);
}
printf("/n");
}
return 0;
}
poj1101
最新推荐文章于 2020-04-14 21:20:15 发布