本文共 1373 字,大约阅读时间需要 4 分钟。
有一个n*m的棋盘(1<n,m<=400),在某个点上有一个马,要求你计算出马到达棋盘上任意一个点最少要走几步
一行四个数据,棋盘的大小和马的坐标
输出格式:一个n*m的矩阵,代表马到达某个点最少要走几步(左对齐,宽5格,不能到达则输出-1)
3 3 1 1
0 3 2 3 -1 1 2 1 4
题解:直接BFS即可,唯一的wa点是宽五格。
AC代码:
/** @Author: 王文宇* @Date: 2018-03-10 18:16:18* @Last Modified by: 王文宇* @Last Modified time: 2018-03-10 22:33:37*/#includeusing namespace std;const int maxn =405;const int inf = 100000000;#define _for(i,a,b) for(int i=a;i<=b;i++)int n,m,ans,sx,sy,a[maxn][maxn];int xx[] = {1,2,2,1,-1,-2,-2,-1},yy[] = {-2,-1,1,2,2,1,-1,-2};struct node{ int x,y;}b[maxn];queue Q;int main(int argc, char const *argv[]){ node begin; cin>>n>>m>>begin.x>>begin.y; _for(i,1,n) { _for(j,1,m)a[i][j]=-1; } a[begin.x][begin.y]=0; Q.push(begin); while(!Q.empty()) { node now = Q.front(); Q.pop(); _for(i,0,7) { int nowx = now.x+xx[i]; int nowy = now.y+yy[i]; if(nowx>=1&&nowx<=n&&nowy<=m&&nowy>=1&&a[nowx][nowy]==-1) { a[nowx][nowy]=a[now.x][now.y]+1; node next; next.x=nowx; next.y=nowy; Q.push(next); } } } _for(i,1,n) { _for(j,1,m) { printf("%-5d",a[i][j]); } cout<
转载地址:http://snhpi.baihongyu.com/