struct Position
{
Position(int posy, int posx) : y(posy), x(posx) { }
int y;
int x;
};
vector<vector<int>> knightlOnAChessboard(int n)
{
vector<vector<int>> result = vector<vector<int>>(n - 1, vector<int>(n -1));
for (int y = 1; y < n; y++)
{
for (int x = 1; x < n; x++)
{
vector<Position> directions = { Position(y,x),
Position(x,y),
Position(-y,-x),
Position(-x,-y),
Position(-y,x),
Position( x,-y),
Position(y,-x),
Position(-x,y) };
result[y - 1][x - 1] = bfs(n, directions);
}
}
return result;
}
int bfs(int n, vector<Position>& directions)
{
bool visited[25][25] = {};
vector<vector<int>> graph = vector<vector<int>>(n, vector<int>(n,-1));
queue<Position> q;
q.push(Position(0, 0));
visited[0][0] = true;
graph[0][0] = 0;
while (!q.empty())
{
Position currPos = q.front();
q.pop();
for (Position& dir : directions)
{
Position nextPos = { currPos.y + dir.y , currPos.x + dir.x };
if (nextPos.y == n - 1 && nextPos.x == n - 1)
return graph[currPos.y][currPos.x] + 1;
if (canGo(n, nextPos) && !visited[nextPos.y][nextPos.x])
{
graph[nextPos.y][nextPos.x] = graph[currPos.y][currPos.x] + 1;
visited[nextPos.y][nextPos.x] = true;
q.push(nextPos);
}
}
}
return graph[n - 1][n - 1];
}
bool canGo(int n, Position nextPos)
{
if (nextPos.x < 0 || n <= nextPos.x)
return false;
if (nextPos.y < 0 || n <= nextPos.y)
return false;
return true;
}