P1443 The traversal of horse【BFS】

https://www.luogu.com.cn/problem/P1443

Title description

There is a chessboard of n*m (1<n,m<=400), there is a horse at a certain point, and you are required to calculate the minimum number of steps the horse has to take to reach any point on the chessboard

Input format

Four data in one row, the size of the chessboard and the coordinates of the horse

Output format

An n*m matrix, representing that the horse must walk at least a few steps to reach a certain point (aligned to the left, 5 grids wide, output -1 if it cannot reach)

Sample input and output

Enter #1 to copy

3 3 1 1

Output #1 copy

0    3    2    
3    -1   1    
2    1    4    

Solution: Under normal BFS, every direction you can walk is saved, and the map that needs to be output is updated. The writing method of BFS is the general writing method. Note that the output needs to be 5 grids wide. I used cin at the beginning, but I was not familiar with formatted output, so I changed it to scanf/printf input and output.

#include <stdio.h>
#include <string.h>
#include<bits/stdc++.h>

using namespace std;
typedef long long ll;
int mp[410][410];
int vis[410][410];
struct node
{
    int x,y,step;
} w,l;

int dx[] = {-1,-1,-2,-2,1,1,2,2};
int dy[] = {-2,2,-1,1,-2,2,1,-1};
void bfs(int sx, int sy,int n, int m)
{
    memset(vis,0,sizeof(vis));
    memset(mp,-1,sizeof(mp));
    queue<node>q;
    w.x = sx;
    w.y = sy;
    w.step = 0;
    q.push(w);
    vis[w.x][w.y] = 1;
    mp[sx][sy] = 0;
    while(!q.empty())
    {
        w = q.front();
        q.pop();
        for(int i = 0; i < 8; i ++)
        {
            int tx = dx[i] + w.x;
            int ty = dy[i] + w.y;
            if(tx >= 1 && tx <= n && ty >= 1 && ty <= m && vis[tx][ty] == 0)
            {
                l.x = tx;
                l.y = ty;
                l.step = w.step+1;
                q.push(l);
                vis[tx][ty] = 1;
                mp[tx][ty] = l.step;
            }
        }
    }
}
int main()
{
    int n,m,sx,sy;
//    cin >> n >> m >> sx >> sy;
    scanf("%d %d %d %d", &n,&m,&sx,&sy);
    bfs(sx,sy,n,m);
    for(int i = 1; i <= n; i ++)
    {
        for(int j = 1; j <= m; j ++)
        {
//            if(j == 1)
//                cout << mp[i][j];
//            else
//                cout << "    " << mp[i][j] ;
            printf("%-5d",mp[i][j]);
        }
        printf("\n");
    }
    return 0;
}

 

Guess you like

Origin blog.csdn.net/Mercury_Lc/article/details/108903104