洛谷P1443 馬的遍歷 簡單BFS

洛谷P1443 傳送門

這題比較水,主要是要學一下優先隊列和結構體一起使用的方法還有重載結構體的優先級


在這裏插入圖片描述


水題,初始化地圖爲-1,然後八個方向的bfs搜索即可

代碼如下:

#include <stdio.h>
#include <cstring>
#include <iostream>
#include <string>
#include <cmath>
#include <algorithm>
#include <cstdlib>
#include <queue>
#include <deque>
#include <cstring>
#include <iterator>
#include <set>
#include <map>
#define ll long long
using namespace std;
int mp[405][405];
int vis[405][405];
int mov[8][2] = {-2, -1, 2, 1, 2, -1, -2, 1, 1, 2, -1, -2, 1, -2, -1, 2};
int n, m, sx, sy;

struct horse
{
    int x, y, step;
} a, b;
queue<horse> q;
void bfs()
{
    while (!q.empty())
    {
        a = q.front();
        q.pop();
        mp[a.x][a.y] = a.step;
        for (int i = 0; i < 8; i++)
        {
            int xx = a.x + mov[i][0];
            int yy = a.y + mov[i][1];
            if (xx < 1 || yy < 1 || xx > n || yy > m || vis[xx][yy])
                continue;
            vis[xx][yy] = 1;
            b.x = xx;
            b.y = yy;
            b.step = a.step + 1;
            q.push(b);
        }
    }
}
int main()
{
    cin >> n >> m >> sx >> sy;
    memset(mp, -1, sizeof(mp));
    a.x = sx;
    a.y = sy;
    a.step = 0;
    q.push(a);
    vis[sx][sy] = 1;
    bfs();
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            printf("%-5d", mp[i][j]);
        cout << endl;
    }
    return 0;
}
發佈了55 篇原創文章 · 獲贊 54 · 訪問量 7406
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章