洛谷 P 1443马的遍历

洛谷 P 1443马的遍历

题目链接

#include 
using namespace std;
int xx[] = {2, 2, 1, 1, -1, -1, -2, -2};
int yy[] = {1, -1, 2, -2, 2, -2, 1, -1};
int n, m, sx, sy;
int mp[410][410];
struct Node
{
    int x, y, s;
};
int main()
{
    scanf("%d%d%d%d", &n, &m, &sx, &sy);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            mp[i][j] = -1;
        }
    }
    queue<Node> q;
    q.push((Node){sx, sy, 0});
    mp[sx][sy] = 0;
    while (!q.empty())
    {
        for (int i = 0; i < 8; i++)
        {
            int dx = xx[i] + q.front().x;
            int dy = yy[i] + q.front().y;
            if (dx >= 1 && dx <= n && dy >= 1 && dy <= m && mp[dx][dy] == -1)
            {
                q.push((Node){dx, dy, q.front().s + 1});
                mp[dx][dy] = q.front().s + 1;
            }
        }
        q.pop();
    }
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            printf("%-5d", mp[i][j]);
        }
        printf("\n");
    }
    return 0;
}

这是我搞了这么久做出来的第一个BFS的题目,终于有了一些成果。

你可能感兴趣的:(深度优先,链表,算法)