[10] 诡异的楼梯
题意:如上图,需要注意的是可以原地停留,也就是说可以等楼梯转向后再走下一步。
算法:BFS
问题:一开始输入就写错了,因为是字符,所以如果用scanf每一个换行都需要加个getchar,或者用cin方便一些。之后才是我debug了一万年的点,就是楼梯的vis不能变成1,不然会有问题。(也就是说楼梯是可以重复走的)首先,这里无需担心bfs死循环的问题,因为只要将楼梯两端的区域标记走过即可。然后,由于本问题与其它问题不同,是可以停留的,所以BFS的每层原先相同的元素可能会出现错位,如果楼梯被标记了,之前选择停留等待的下一步就走不下去了。
思路:除上面的部分以外,同普通BFS,设置结构体pos表示每个点的信息,存入队列,每层清空,每层更新数据,每层的元素时间都一样,所以当找到符合条件的,就一定是耗时最少的。
代码:ac
#include<bits/stdc++.h>
using namespace std;
int m, n;
int sx, sy, ex, ey;
char Map[25][25];
int vis[25][25];
int dir[4][2] = { {0,1},{0,-1},{1,0},{-1,0} };
struct pos {
int x, y;
int time;
};
void bfs();
int main()
{
while (scanf("%d%d", &m, &n) != EOF) {
for (int i = 1; i <= m; i++)
{
for (int j = 1; j <= n; j++)
{
cin >> Map[i][j];
vis[i][j] = 0;
if (Map[i][j] == 'S') {
sx = i, sy = j;
vis[i][j] = 1;
}
if (Map[i][j] == 'T') {
ex = i, ey = j;
}
}
}
Map[ex][ey] = '.';/*便于判断移动条件*/
bfs();
}
return 0;
}
void bfs()
{
pos cur, nex;
cur.x = sx, cur.y = sy;
cur.time = 0;
queue<pos>qu;
qu.push(cur);
while (!qu.empty()) {
cur = qu.front();
qu.pop();
if (cur.x == ex && cur.y == ey) {
printf("%d\n", cur.time);
return;
}
for (int i = 0; i < 4; i++) {
nex.x = cur.x + dir[i][0];
nex.y = cur.y + dir[i][1];
nex.time = cur.time + 1;
if (nex.x <= m && nex.x >= 1 && nex.y <= n && nex.y >= 1 && vis[nex.x][nex.y] == 0) {
if (Map[nex.x][nex.y] == '|') {
if (((i == 0 || i == 1) && cur.time % 2 == 1) || ((i == 2 || i == 3) && cur.time % 2 == 0)) {
if (Map[nex.x + dir[i][0]][nex.y + dir[i][1]] == '.'&& vis[nex.x + dir[i][0]][nex.y + dir[i][1]]==0) {
vis[nex.x + dir[i][0]][nex.y + dir[i][1]] = 1;
nex.x += dir[i][0];
nex.y += dir[i][1];
qu.push(nex);
}
}
else if (Map[nex.x + dir[i][0]][nex.y + dir[i][1]] == '.') {
nex.x -= dir[i][0];
nex.y -= dir[i][1];
qu.push(nex);
}
else continue;
}
else if (Map[nex.x][nex.y] == '-') {
if (((i == 2 || i == 3) && cur.time % 2 == 1) || ((i == 0 || i == 1) && cur.time % 2 == 0)) {
if (Map[nex.x + dir[i][0]][nex.y + dir[i][1]] == '.'&& vis[nex.x + dir[i][0]][nex.y + dir[i][1]]==0){
vis[nex.x + dir[i][0]][nex.y + dir[i][1]] = 1;
nex.x += dir[i][0];
nex.y += dir[i][1];
qu.push(nex);
}
}
else if (Map[nex.x + dir[i][0]][nex.y + dir[i][1]] == '.') {
nex.x -= dir[i][0];
nex.y -= dir[i][1];
qu.push(nex);
}
else continue;
}
else if (Map[nex.x][nex.y] == '.') {
vis[nex.x][nex.y] = 1;
qu.push(nex);
}
}
}
}
}
没有什么比看到accepted更令人高兴的了……debug太难了……