欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

洛谷 - 马的遍历 (bfs搜索)

程序员文章站 2022-06-11 20:37:31
...

题目传送
题意:
洛谷 - 马的遍历 (bfs搜索)
思路:
这里要注意,由于马是走‘日’字的,也就是马在象棋上的走路方式。
那么这里的方向数组就不止是普普通通的上下左右了,而是8种情况。所以这里的方向数组要变化一下,其他的就是bfs遍历基操了,bfs遍历先到的点,一定是最短的。

#include <bits/stdc++.h>
inline int read(){char c = getchar();int x = 0,s = 1;
while(c < '0' || c > '9') {if(c == '-') s = -1;c = getchar();}
while(c >= '0' && c <= '9') {x = x*10 + c -'0';c = getchar();}
return x*s;}
using namespace std;
#define NewNode (TreeNode *)malloc(sizeof(TreeNode))
#define Mem(a,b) memset(a,b,sizeof(a))
#define lowbit(x) (x)&(-x)
const int N = 5e5 + 10;
const long long INFINF = 0x7f7f7f7f7f7f7f;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-7;
const unsigned long long mod = 998244353;
const double II = acos(-1);
const double PP = (II*1.0)/(180.00);
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef pair<ll,ll> piil;
struct node
{
    int x,y,step;
};
int main()
{
    std::ios::sync_with_stdio(false);
    cin.tie(0),cout.tie(0);
    int x,y,n,m,ans = -1;
    cin >> n >> m >> x >> y;
    int arr[n+5][m+5] = {0},way[8][2] = {{2,1},{2,-1},{-2,-1},{-2,1},{-1,-2},{1,2},{-1,2},{1,-2}},vis[n+5][m+5] = {0};
	//方向数组way
    for(int i = 1;i <= n;i++)
        for(int j = 1;j <= m;j++)
            arr[i][j] = -1;//初始化
    arr[x][y] = 0,vis[x][y] = 1;
    queue<node> q;
    q.push({x,y,0});
    while(!q.empty())
    {
        node t = q.front();
        q.pop();
        for(int i = 0;i < 8;i++)
        {
            int xx = t.x + way[i][0],yy = t.y + way[i][1];
            if(vis[xx][yy] || xx <= 0 || yy <= 0 || xx > n || yy > m)
                continue;
            vis[xx][yy] = 1;
            arr[xx][yy] = t.step+1;//记录最短
            q.push({xx,yy,t.step+1});
        }
    }
    for(int i = 1;i <= n;i++)
        for(int j = 1;j <= m;j++)
            j == m ? printf("%-5d\n",arr[i][j]) : printf("%-5d",arr[i][j]);
}