迷宫的最短路径问题的翻版, 输出是个坑, 左对齐五个字符。
#include <iostream>
#include <string>
#include <queue>
#include <iomanip>
using namespace std;
struct Coordinate{
int row;
int col;
};
const int MAX_SIZE = 400, INF = 2333333;
Coordinate start, goal;
//马的八个方向
Coordinate dir[8] = {{-2, -1}, {-2, 1}, {-1, 2}, {1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}};
char maze[MAX_SIZE + 1][MAX_SIZE + 1];
int dis[MAX_SIZE + 1][MAX_SIZE + 1];
int N, M;
queue<Coordinate> que;
void bfs()
{
while (que.size()){
Coordinate head = que.front();
que.pop();
for (int i = 0; i < 8; i++){
Coordinate tmp;
tmp.row = head.row + dir[i].row;
tmp.col = head.col + dir[i].col;
if (tmp.row >= 1 && tmp.row <=N && tmp.col >= 1 && tmp.col <= M &&
dis[tmp.row] [tmp.col] == INF){
que.push(tmp);
dis[tmp.row][tmp.col] = dis[head.row][head.col] + 1;
}
}
}
}
int main()
{
cin >> N >> M >> start.row >> start.col;
for (int i = 1; i <= N; i++)
for (int j = 1; j <= M; j++)
dis[i][j] = INF;
que.push(start);
dis[start.row][start.col] = 0;
bfs();
for (int i = 1; i <= N; i++){
for (int j = 1; j <= M; j++){
if (dis[i][j] != INF){
cout << left << setw(5) <<dis[i][j];
}
else {
cout << left << setw(5) << -1;
}
if (j == M)
cout << endl;
}
}
return 0;
}