题解 P2208 【[USACO13OPEN]重力异常What's Up With Gra…】

· · 题解

思路和部分代码是借鉴的... 就是一个走迷宫,只不过特殊处理一下重力的相关过程 代码里边有注释,写的还蛮清晰的...

#include<map>
#include<stack>
#include<cmath>
#include<queue>
#include<cstdio>
#include<vector> 
#include<cstring>
#include<iostream>
#include<algorithm>
using std::cin;
using std::cout;
void gkd()
{
    std::ios::sync_with_stdio(false);
    cout.tie(NULL);
}
char map[555][555];
bool vis[555][555][4];
struct node
{
    int x, y, g, sum;//当前坐标,当前重力状态:1为上 -1为下 
}now, top;
std::deque<node> q;
int n, m, x, y;
signed main()
{
    //gkd();
    cin >> n >> m;
    for(int i = 1; i <= n; i++)
    {
        scanf("%s",map[i]+1);
        for(int j = 1; j <= m; j++)
        {
            if(map[i][j] == 'C')
                x = i, y = j;
        }
    }
    now.x = x, now.y = y, now.g = 1, now.sum = 0;
    q.push_back(now);
    while(!q.empty())
    {
        top = q.front();
        q.pop_front();
        now.x = top.x + top.g,
        now.y = top.y,
        now.g = top.g,
        now.sum = top.sum; 
        if(map[top.x][top.y] == 'D')
            return cout << top.sum, 0;
        if(top.x + top.g < 1 || top.x + top.g > n || top.y < 1 || top.y > m)
            continue;//越了上下边界 
        vis[top.x][top.y][top.g + 1] = 1;
        if(map[top.x  + top.g][top.y] == '#')//脚下(头上)能不能踩 
        {
            now.x = top.x, 
            now.y = top.y + 1, 
            now.g = top.g, 
            now.sum = top.sum;
            if(!vis[top.x][top.y + 1][top.g + 1] && map[top.x][top.y + 1] != '#')
                q.push_front(now);//判断当前的重力下右移 

            now.x = top.x, 
            now.y = top.y - 1, 
            now.g = top.g, 
            now.sum = top.sum;
            if(!vis[top.x][top.y - 1][top.g + 1] && map[top.x][top.y - 1] != '#')
                q.push_front(now);//判断当前重力下左移 

            now.x = top.x, 
            now.y = top.y, 
            now.g =- top.g, 
            now.sum = top.sum + 1;
            if(!vis[top.x][top.y][-top.g + 1])
                q.push_back(now);//翻转重力         
        } 
        else
            q.push_front(now);//如果脚下不是可以踩的格子,那么就继续下落或者上落    
    }
    cout << -1 << '\n';
}