poj 3083

解决好方向问题就ok


#include 
#include 
#include 
#include 
#include 
using namespace std;

#define met(a, b) memset(a, b, sizeof(a))

const int N = 45;

bool flag;
char g[N][N];
int m, n, ans, vis[N][N];
int dir[4][2] = {0, -1, -1, 0, 0, 1, 1, 0};
struct node {int x, y, t;};

void dfs (int x, int y, int x1, int y1, int d);
void bfs (node sa, node en);

int main ()
{
    int t;
    cin >> t;
    while (t--)
    {
        node sa, en;
        cin >> n >> m;
        for (int i=0; i> g[i][j];
            if (g[i][j] == 'S') sa = (node){i, j};
            if (g[i][j] == 'E') en = (node){i, j};
        }
        ans = 1; flag = false;
        dfs (sa.x, sa.y, en.x, en.y, 0);
        cout << ans << " ";
        ans = 1; flag = false;
        dfs (en.x, en.y, sa.x, sa.y, 0);
        cout << ans << " ";
        met (vis, false);
        bfs (sa, en);
    }
    return 0;
}

void dfs (int x, int y, int x1, int y1, int d)
{
    if (flag) return;
    if (x == x1 && y == y1) {flag = true; return;}

    d = (d + 3) % 4;

    for (int i=d; i= 0 && xx < m && yy >= 0 && yy < n && g[xx][yy] != '#')
        {
            ans++;
            dfs (xx, yy, x1, y1, i%4);
            if (flag) return;
        }
    }
}

void bfs (node sa, node en)
{
    queue  que;
    sa.t = 1;
    que.push(sa);
    vis[sa.x][sa.y] = true;
    while (que.size())
    {
        sa = que.front(); que.pop();
        if (sa.x == en.x && sa.y == en.y) {cout << sa.t << endl; return;}
        for (int i=0; i<4; i++)
        {
            node q = sa;
            q.x += dir[i][0], q.y += dir[i][1];
            if (q.x >= 0 && q.x < m && q.y >= 0 && q.y < n && !vis[q.x][q.y] && g[q.x][q.y] != '#')
            {
                vis[q.x][q.y] = true;
                q.t = sa.t + 1;
                que.push(q);
            }
        }
    }
}


你可能感兴趣的:(poj 3083)