洛谷P1443马的遍历
原题连接:马的遍历
#include <bits/stdc++.h>
#define _for(i, a, b) for( int i = a; i < b; ++i)
using namespace std;
typedef long long ll;
const int maxn = 400;
const int mod = 1e9+7;
int graph[maxn][maxn];
int _go[8][2] = {{2, 1},{2, -1}, {-2, 1}, {-2, -1}, {1, 2}, {1, -2}, {-1, 2}, {-1, -2}};
int n, m, x, y, size, step;
queue < pair<int, int> > que;
pair <int, int> p;
int main(void){
cin >> n >> m >> x >> y;
memset(graph, -1, sizeof(graph));
graph[x][y] = 0;
p = make_pair(x,y);
que.push(p);
size = 1;
step = 1;
while(!que.empty()){
int tmp = 0;
_for(i, 0, size){
int mx = que.front().first;
int my = que.front().second;
que.pop();
_for(i, 0, 8){
int _x = mx + _go[i][0], _y = my + _go[i][1];
if(_x < 1 || _x > n || _y < 1 || _y > m || graph[_x][_y] >= 0)
continue;
p = make_pair(_x, _y);
que.push(p);
graph[_x][_y] = step;
tmp++;
}
}
size = tmp;
step++;
}
_for(i, 1, n+1){
_for(j, 1, m+1){
printf("%-5d", graph[i][j]);
}
printf("\n");
}
return 0;
}