https://www.luogu.org/problemnew/show/P1443
思路:深度遍历,能走的就走,裸模板
#include <iostream>
#include <cstdio>
#include <cstring>
#include<iomanip>
#include<string>
#include<queue>
using namespace std;
struct node
{
int x, y;
};
queue<node>Q;
int n, m,sx, sy;
int a[401][401];
//int step = 1;
int dx[]={-2, -2, -1, 1, 2, 2, 1, -1};//这个自己画图可以看是怎么得来的
int dy[]={-1, 1, 2, 2, 1, -1, -2, -2};
void bfs(int x, int y)
{
a[x][y] = 0;
node tmpnode;
tmpnode.x = x;
tmpnode.y = y;
Q.push(tmpnode);
while(!Q.empty())
{
//cout<<"haha";
//system("pause");
node fnode = Q.front();
Q.pop();
for(int i = 0; i < 8; i++)
{
int x0 = fnode.x +dx[i];
int y0 = fnode.y + dy[i];
if(x0 >= 1 && x0 <= n && y0>=1 && y0<=m && a[x0][y0] == -1)
{
//cout<<x0<<" "<<y0<<" "<<a[fnode.x][fnode.y] + 1<<endl;
//system("pause");
a[x0][y0] = a[fnode.x][fnode.y]+1;//步数是父节点+1
tmpnode.x = x0;
tmpnode.y = y0;
Q.push(tmpnode);
}
}
//step++;
}
}
int main()
{
ios::sync_with_stdio (false);
cin>>n>>m>>sx>>sy;
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
a[i][j] = -1;
bfs(sx, sy);
for(int i = 1; i <= n; i++)
{
for(int j = 1; j <= m; j++)
cout<<left<<setw(5)<<a[i][j];//左对齐和宽度是5输出
//cout<<a[i][j]<<" ";
cout<<endl;
}
//system("pause");
}