HDU_1010(dfs)

具体题目及要求:
《HDU_1010(dfs)》
输入输出示例:
《HDU_1010(dfs)》
这是个经典的基础搜索问题,很快就用bfs写好了代码,但提交总是超时,后来才知道有奇偶剪枝这个判断,加上后,ac。
具体代码如下:

#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;
const int dir[4][2] = {{0, 1}, {0, -1},
                       {1, 0}, {-1, 0}};
int temp[4];
int flag = 0;
int m, n, t;
bool a[8][8];
char graph[10][10];
void dfs(int x, int y, int step, int t)
{
    if (graph[x][y] == 'D' && step == t) {
        flag = 1;
        return;
    }
    if (step == t)
        return;
    if (flag == 1)
        return;
    for (int i = 0; i < 4; i++) {
        int nx = x + dir[i][0];
        int ny = y + dir[i][1];
        if (nx < 0 || nx > n - 1 || ny < 0 || ny > m - 1 || a[nx][ny] == 1 || graph[nx][ny] == 'X')
            continue;
        a[x][y] = 1;
        dfs(nx, ny, step + 1, t);
        a[x][y] = 0;
    }
}
int main()
{
    while (cin >> n >> m >>t && t && n && m) {
        memset(a, 0, sizeof(a));
        for (int i = 0; i < n; i++)
            for (int j = 0; j < m; j++) {
                cin >>graph[i][j];
                if (graph[i][j] == 'S') {
                    temp[0] = i;
                    temp[1] = j;
                }
                if (graph[i][j] == 'D') {
                    temp[2] = i;
                    temp[3] = j;
                }
            }
    int xx = abs(temp[2] - temp[0]);
    int yy = abs(temp[3] - temp[1]);
    if ((t - (xx + yy)) % 2 == 0)    // 奇偶剪枝
        dfs(temp[0], temp[1], 0, t);
    if (flag)
        cout << "YES" << endl;
    else
        cout << "NO" << endl;
    flag = 0;
    }
    return 0;
}
点赞