- 问题一
- 代码
- 问题二(蓝桥杯s型填数)
- 代码
#include问题二(蓝桥杯s型填数)using namespace std; int main() { int n; cin >> n; vector > res(n + 2, vector (n + 2,0)); int count = 1; res[1][n] = 1; int x = 1; int y = n; while(count < n *n) { //向下走 while(x + 1 <= n && !res[x + 1][y]) { res[++x][y] = ++count; } //向左 while(y - 1 > 0 && !res[x][y - 1]) { res[x][--y] = ++count; } //向上 while(x - 1 > 0 && !res[x - 1][y]) { res[--x][y] = ++count; } //向右 while(y + 1 <= n && !res[x][y + 1]) { res[x][++y] = ++count; } } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n; j++) { if(j != n) { cout << " "; } else { cout << endl; } } } return 0; }
输入:一个数字n
输出:如图所示的上三角(n*n)
#includeusing namespace std; int main() { int n; cin >> n; vector > res(n + 2, vector (n + 2,0)); int count = 1; res[1][1] = 1; int x = 1; int y = 1; while(count < n * (n + 1) / 2) { y++; //向左 //斜向下走 while(x != 0 && y != 0 && !res[x + 1][y - 1]) { res[x++][y--] = ++count; } y++; //向下 //斜向上走 while(x != 0 && y != 0 && !res[x - 1][y + 1]) { res[x--][y++] = ++count; } //跳回到输出的矩阵内,好继续后面的while循环 x++; y--; } for(int i = 1; i <= n; i++) { for(int j = 1; j <= n - i + 1; j++) { cout << res[i][j]; if(j != n - i + 1) { cout << " "; } else { cout << endl; } } } return 0; }
更多汇总填数问题请移步–>我的语雀



