问题 B: DFS or BFS?

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <stack>
#include <climits>
#include <vector>
#include <cmath>
#include <queue>

using namespace std;

struct node {
    int x, y, step;
};

int d_x[9] = {-1, -1, 0, 1, 1, 1, 0, -1, 0};
int d_y[9] = {0, 1, 1, 1, 0, -1, -1, -1, 0};

int n, start_x, start_y, end_x, end_y;

char map[10][10];
//bool flags[10][10] = {false};

bool flag;

bool judge(int x, int y) {
    if (x < 1 || x > 8 || y < 1 || y > 8) return false;
    if (map[x][y] == 'S') return false;
    if (x > 1 && map[x - 1][y] == 'S') return false;

    return true;
}

void refresh(int times) {
    for (int i = 8; i > times; --i) {
        for (int j = 1; j <= 8; ++j) {
            map[i][j] = map[i - 1][j];
        }
    }
    for (int k = 1; k <= 8; ++k) {
        map[times][k] = '.';
    }
}


void solve() {
    queue<node> q;
    q.push(node{start_x, start_y, 1});

    int now_step = 1;
    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        if (t.step == 8) {
            flag = true;
            return;
        }

        if (now_step != t.step) {
            refresh(now_step);
            now_step = t.step;

        }

        if (t.x == end_x && t.y == end_y) {
            flag = true;
            return;
        }
        for (int i = 0; i < 9; ++i) {
            int new_x = t.x + d_x[i];
            int new_y = t.y + d_y[i];

            if (judge(new_x, new_y)) {
                q.push(node{new_x, new_y, now_step + 1});
            }
        }


    }

}

int main() {

    while (scanf("%d", &n) != EOF) {


        for (int i = 0; i < n; ++i) {
            flag = false;
            for (int j = 1; j <= 8; ++j) {
                for (int k = 1; k <= 8; ++k) {
                    char temp;
                    scanf(" %c", &temp);

                    if (temp == 'U') {
                        start_x = j;
                        start_y = k;
                        temp = '.';
                    }
                    if (temp == 'A') {
                        end_x = j;
                        end_y = k;
                        temp = '.';
                    }
                    map[j][k] = temp;
                }
            }

            solve();

            if (flag) printf("Case #%d: Yes\n", i + 1);
            else printf("Case #%d: No\n", i + 1);
        }


    }

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值