90分求助,最后一个点WA(输出了一个以上的零,但找不出问题)。
查看原帖
90分求助,最后一个点WA(输出了一个以上的零,但找不出问题)。
664843
zhaozhijieleo楼主2022/10/27 22:40
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
using namespace std;
const int N = 401;

struct horse_pos
{
        int pos_x = 0, pos_y = 0;
};

int n, m;
int horse_x, horse_y;
int answer[N][N];
bool visit[N][N];

int ctrl_X[] = {0, 1, 1, -1, -1, 2, -2, 2, -2};
int ctrl_Y[] = {0, 2, -2, 2, -2, 1, 1, -1, -1};

bool check(horse_pos pos);
void init();
void BFS();
void print();

int main(int argc, char const *argv[])
{
        ios::sync_with_stdio(false);
        cin.tie(0), cout.tie(0);
        init(), BFS(), print();
        return 0;
}

bool check(horse_pos pos)
{
        int x = pos.pos_x, y = pos.pos_y;

        if (x < 1 || x > n || y < 1 || y > m)
                return false;
        else
                return true;
}

void init()
{
        cin >> n >> m;
        cin >> horse_x >> horse_y;
}

void BFS()
{
        queue<horse_pos> que;
        horse_pos start;
        start.pos_x = horse_x, start.pos_y = horse_y;
        que.push(start), visit[horse_x][horse_y] = true;
        answer[horse_x][horse_y] = 0;

        while (que.size())
        {
                horse_pos now = que.front();
                int now_x = now.pos_x, now_y = now.pos_y;
                que.pop();

                for (int i = 1; i <= 8; i++)
                {
                        horse_pos tmp_next;
                        tmp_next.pos_x = now_x + ctrl_X[i];
                        tmp_next.pos_y = now_y + ctrl_Y[i];

                        if (check(tmp_next) && !visit[tmp_next.pos_x][tmp_next.pos_y])
                        {
                                visit[tmp_next.pos_x][tmp_next.pos_y] = true, que.push(tmp_next);
                                answer[tmp_next.pos_x][tmp_next.pos_y] = answer[now_x][now_y] + 1;
                        }
                }
        }
}

void print()
{
        for (int i = 1; i <= n; i++, cout << "\n")
                for (int j = 1; j <= m; j++, cout << " ")
                        cout << (answer[i][j] == 0 && (i != horse_x && j != horse_y) ? -1 : answer[i][j]);
}

究竟是哪一步错了,请求讲解,谢谢。

2022/10/27 22:40
加载中...