BFS求助
查看原帖
BFS求助
787888
Channel_Choo楼主2023/8/10 09:40
#include <iostream>
#include <queue>
#include <string.h>
#include <cstdio>
using namespace std;
int c[405][405];
bool vis[405][405];
int dx[8] = {-2, -2, 2, 2, 1, -1, 1, -1};
int dy[8] = {-1, 1, -1, 1, 2, -2, -2, 2};
int n, m, x, y;
struct Point
{
    int x, y;
};
queue<Point> q;
void bfs()
{
    q.push((Point){x, y});
    c[x][y] = 0;
    vis[x][y] = true;
    while (q.size() > 0)
    {
    	Point now = q.front();
        q.pop();
        for (int i = 0;i < 8;i++)
        {
            int nx = now.x + dx[i];
            int ny = now.y + dy[i];
            if (nx >= 1 && ny <= n && ny >= 1 && ny <= m && !vis[nx][ny])
            {
                q.push((Point){nx,ny});
                c[nx][ny] = c[now.x][now.y] + 1;
                vis[nx][ny] = true;
            }
        }
    }
}
int main()
{
    cin >> n >> m >> x >> y;
    bfs();
    for (int i = 1;i <= n;i++)
    {
        for (int j = 1;j <= m;j++)
        {
            printf("%-5d", c[i][j]);
        }
        cout << endl;
    }
    return 0;
}

输入

3 3 1 1

我的输出

0     3     2


标准输出

0     3     2
3     -1    1
2     1     4

不知道哪里出问题了QwQ

2023/8/10 09:40
加载中...