DFS 专题 Tempter of the Bone

这道题的剪枝:奇偶性,曼哈顿距离类型的。不剪会超时。

# include <cstdio>

# include <cstring>



using namespace std;



# define N 7 + 3

# define ABS(x) (((x)>0)?(x):(-(x)))



int si, sj, gi, gj;

int n, m, T;

char g[N][N];

bool vis[N][N];

bool finished;



const int dir[][2] = {{0,1}, {1,0}, {0,-1}, {-1,0}};



void dfs(int x, int y, int t)

{

    int tmp = ABS(x-gi)+ABS(y-gj);

    if (tmp > t) return;

    if (tmp%2 != t%2) return ;

    if (t == 0) finished = (x == gi && y == gj);

    else for (int d = 0; d < 4; ++d)

    {

        int nx = x + dir[d][0], ny = y + dir[d][1];

        if (1<=nx&&nx<=n && 1<=ny&&ny<=m && g[x][y]!='X' && vis[nx][ny]==false)

        {

            vis[nx][ny] = true;

            dfs(nx, ny, t-1);

            if (finished) return ;

            vis[nx][ny] = false;

        }

    }

}



void init(void)

{

    int in;



    in = 0;

    for (int i = 1; i <= n; ++i)

    {

        scanf("%s", g[i]+1);

        memset(vis[i], false, sizeof(vis[0][0])*(m+1));

        for (int j = 1; in<2 && j <= m; ++j)

            if(g[i][j] == 'S') si = i, sj = j, ++in;

            else if (g[i][j] == 'D') gi = i, gj = j, ++in;

    }

}



void solve(void)

{

    finished = false;

    vis[si][sj] = true, dfs(si, sj, T);

    puts(finished ? "YES":"NO");

}



int main()

{

    while (scanf("%d%d%d", &n, &m, &T), n || m || T)

    {

        init();

        solve();

    }



    return 0;

}

/**/

你可能感兴趣的:(DFS)