P1443 horse traversal (bfs)

Copyright: private individuals do question summed up ~ https://blog.csdn.net/tb_youth/article/details/90948017

https://www.luogu.org/problemnew/show/P1443
subject description
has n * m a board (1 <n, m <= 400), there is a horse at some point, reach the requirements to run the board you calculate on any point at least a few steps to go

Input and output format
input format:
a row of four data, and the coordinates of the board size of the horse

Output format:
a matrix of n * m, horse reaches a point representative of a minimum of steps to go (left, 5 wide grid, the output does not reach -1)

Sample Input Output
Input Sample # 1:
3311
Output Sample # 1:
0. 3 2
. 3 -1 1
2 1. 4
// bare bfs, just to record it when it ~
ac_code:

#include <bits/stdc++.h>
using namespace std;

struct point
{
    int x,y;
    int cnt;
    point(int xx,int yy,int ct = 0):x(xx),y(yy),cnt(ct){}
};
int step[8][2]=
{
    -2,-1,-1,-2,-2,1,-1,2,
    1,-2,2,-1,1,2,2,1
};
int n,m,sx,sy;
bool vis[405][405];
int mp[405][405];
void bfs()
{
    point s(sx,sy);
    queue<point>q;
    q.push(s);
    vis[s.x][s.y] = true;
    while(!q.empty())
    {
        point k = q.front();
        q.pop();
        for(int i = 0; i < 8; i++)
        {
            int xx = k.x + step[i][0];
            int yy = k.y + step[i][1];
            if(xx<1||xx>n||yy<1||yy>m||vis[xx][yy])
                continue;
            vis[xx][yy] = true;
            mp[xx][yy] = k.cnt+1;
            q.push(point(xx,yy,k.cnt+1));
        }
    }
}
int main()
{
    cin>>n>>m>>sx>>sy;
    bfs();
    cout.setf(ios::left);
    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
        {
            cout.width(5);
            if(i == sx && j == sy)
            {
                cout<<0;
            }
            else
            {
              cout<<(mp[i][j] ? mp[i][j] : -1);
            }
        }
        cout<<endl;
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/tb_youth/article/details/90948017