P1443 馬的遍歷

題目描述

有一個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 <stdio.h>
#include <iostream>
#include <algorithm>
#include <queue>
using namespace std;

int chessboard[401][401], vis[401][401];

int main() {
	int n, m, x, y,
		step[8][2] = { {-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2},{-1,-2},{-2,-1} };
	queue < pair<int, int> >q;
	fill(chessboard[0], chessboard[0] + 401 * 401, -1);
	cin >> n >> m >> x >> y;
	q.push(make_pair(x, y));
	vis[x][y] = 1, chessboard[x][y] = 0;
	while (!q.empty()) {
		for (int i = 0; i < 8; ++i) {
			int xx = q.front().first + step[i][0];
			int yy = q.front().second + step[i][1];
			if (!vis[xx][yy] && xx > 0 && xx <= n && yy > 0 && yy <= m) {
				q.push(make_pair(xx, yy));
				vis[xx][yy] = 1, chessboard[xx][yy] = chessboard[q.front().first][q.front().second] + 1;
			}
		}
		q.pop();
	}
	for (int i = 1; i <= n; ++i) {
		for (int j = 1; j <= m; ++j)
			printf("%-5d", chessboard[i][j]);
		cout << endl;
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章