洛谷 P1443 马的遍历 #图的遍历与连通性 BFS#

版权声明:while (!success) try(); https://blog.csdn.net/qq_35850147/article/details/89299025

题目描述

有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步

输入输出格式

输入格式:

一行四个数据,棋盘的大小和马的坐标

输出格式:

一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)

输入输出样例

输入样例#1: 复制

3 3 1 1

输出样例#1: 复制

0    3    2    
3    -1   1    
2    1    4

题解

#include <bits/stdc++.h>

using namespace std;

const int dx[] = {1, 1, 2, 2, -1, -1, -2, -2};
const int dy[] = {2, -2, 1, -1, 2, -2, 1, -1};
int n, m, a, b;
int dis[401][401];
struct cor
{
    int x, y;
};

bool is_inside(int i, int j)
{
    return i >= 1 && i <= n && j >= 1 && j <= m ? true : false;
}

void BFS(int i, int j)
{
    queue<cor> q;
    q.push(cor{i, j});
    while (!q.empty())
    {
        cor c = q.front();
        q.pop();
        for (int i = 0; i < 8; i++)
        {
            if (is_inside(c.x + dx[i], c.y + dy[i]) && dis[c.x + dx[i]][c.y + dy[i]] == -1)
            {
                dis[c.x + dx[i]][c.y + dy[i]] = dis[c.x][c.y] + 1;
                q.push(cor{c.x + dx[i], c.y + dy[i]});
            }
        }
    }
}

int main()
{
    memset(dis, -1, sizeof(dis));
    scanf("%d%d%d%d", &n, &m, &a, &b);
    dis[a][b] = 0;
    BFS(a, b);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
            printf("%-5d", dis[i][j]);        
        putchar('\n');
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35850147/article/details/89299025
今日推荐