#include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include using namespace std; int GetMoves(int n, int i, int j) { struct Position { int row; int col; int numMoves; }; std::list searchList; searchList.push_back(Position{0, 0, 0}); std::vector visited(n*n, false); visited[0] = true; auto HasVisited = [&visited, n](int row, int col) { return visited[row*n + col]; }; auto SetVisited = [&visited, n](int row, int col) { visited[row*n + col] = true; }; while (searchList.size()) { Position pos = searchList.front(); searchList.pop_front(); if (pos.row == n-1 && pos.col == n-1) { return pos.numMoves; } // upwards on i if (pos.row - i >= 0) { // left & right on j int row = pos.row - i; if (pos.col - j >= 0) { if (!HasVisited(row, pos.col - j)) { searchList.push_back(Position{row, pos.col - j, pos.numMoves + 1}); SetVisited(row, pos.col - j); } } if (pos.col + j <= n-1) { if (!HasVisited(row, pos.col + j)) { searchList.push_back(Position{row, pos.col + j, pos.numMoves + 1}); SetVisited(row, pos.col + j); } } } // downwards on i if (pos.row + i <= n-1) { // left & right on j int row = pos.row + i; if (pos.col - j >= 0) { if (!HasVisited(row, pos.col - j)) { searchList.push_back(Position{row, pos.col - j, pos.numMoves + 1}); SetVisited(row, pos.col - j); } } if (pos.col + j <= n-1) { if (!HasVisited(row, pos.col + j)) { searchList.push_back(Position{row, pos.col + j, pos.numMoves + 1}); SetVisited(row, pos.col + j); } } } // upwards on j if (pos.row - j >= 0) { // left & right on i int row = pos.row - j; if (pos.col - i >= 0) { if (!HasVisited(row, pos.col - i)) { searchList.push_back(Position{row, pos.col - i, pos.numMoves + 1}); SetVisited(row, pos.col - i); } } if (pos.col + i <= n-1) { if (!HasVisited(row, pos.col + i)) { searchList.push_back(Position{row, pos.col + i, pos.numMoves + 1}); SetVisited(row, pos.col + i); } } } // downwards on j if (pos.row + j <= n-1) { // left & right on i int row = pos.row + j; if (pos.col - i >= 0) { if (!HasVisited(row, pos.col - i)) { searchList.push_back(Position{row, pos.col - i, pos.numMoves + 1}); SetVisited(row, pos.col - i); } } if (pos.col + i <= n-1) { if (!HasVisited(row, pos.col + i)) { searchList.push_back(Position{row, pos.col + i, pos.numMoves + 1}); SetVisited(row, pos.col + i); } } } } return -1; } int main(){ int n; cin >> n; // your code goes here for (int i = 1; i <= n - 1; ++i) { for (int j = 1; j <= n - 1; ++j) { printf("%d ", GetMoves(n, i, j)); } printf("\n"); } return 0; }