不太懂马的走法,所以就改了题
假设马只能上下左右四个方向走
样例答案应该是
2 1 2
1 0 1
2 1 2
但是我写的这一坨好像不太对
(里面的tracker变量是用来记录步数的)
#include <iostream>
#include <queue>
#include <cstdio>
using namespace std;
int map[405][405];
int view[405][405];
struct node
{
int row;
int col;
};
queue<node> line;
int total_row;
int total_col;
int start_row, start_col;
int shift_x[] = {0, 0, -1, 1};
int shift_y[] = {1, -1, 0, 0};
int tracker = 0;
int flag = 0;
void bfs(int target_row, int target_col)
{
node start;
start.row = start_row;
start.col = start_col;
view[start_row][start_col] = 1;
line.push(start);
while (!line.empty())
{
int head_row = line.front().row;
int head_col = line.front().col;
int back_row = line.back().row;
int back_col = line.back().col;
tracker++;
if (back_row == target_row && back_col == target_col)
{
flag = 1;
map[target_row][target_col] = tracker;
return;
}
for (int i = 0; i < 4; i++)
{
int x = head_row + shift_x[i];
int y = head_col + shift_y[i];
if (x < 0 || y < 0)
{
continue;
}
if (x >= total_row || y >= total_col)
{
continue;
}
if (view[x][y] == 0)
{
view[x][y] = 1;
node temp;
temp.row = x;
temp.col = y;
line.push(temp);
}
cout << "shit" << endl;
}
line.pop();
}
if (flag == 0)
{
map[start_row][start_col] = -1;
return;
}
}
int main()
{
cin >> total_row >> total_col;
cin >> start_row >> start_col;
for (int i = 0; i < total_row; i++)
{
for (int j = 0; j < total_col; j++)
{
bfs(i, j);
tracker = 0;
}
}
for (int i = 0; i < total_row; i++)
{
for (int j = 0; j < total_col; j++)
{
printf("%-5d", map[i][j]);
}
cout << endl;
}
return 0;
}