#include #include using namespace std;

int main() { int n; cin >> n;

int matrix[n][n];
int startRow = 0, endRow = n-1, startCol = 0, endCol = n-1;
int num = 1;

while (startRow <= endRow && startCol <= endCol) {
    for (int i = startCol; i <= endCol; i++) {
        matrix[startRow][i] = num;
        num++;
    }
    startRow++;
    
    for (int i = startRow; i <= endRow; i++) {
        matrix[i][endCol] = num;
        num++;
    }
    endCol--;
    
    for (int i = endCol; i >= startCol; i--) {
        matrix[endRow][i] = num;
        num++;
    }
    endRow--;
    
    for (int i = endRow; i >= startRow; i--) {
        matrix[i][startCol] = num;
        num++;
    }
    startCol++;
}

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        cout << setw(4) << matrix[i][j];
    }
    cout << endl;
}

return 0;
题目描述:输入n试打印输出nn的回形矩阵每个元素占4位场宽。输入:一行一个整数n1sns20。输出:一个n行n列的回形矩阵。样例组样例输入1:6样例输出1:1 1 1 1 1 11 2 2 2 2 11 2 3 3 2 11 2 3 3 2 11 2 2 2 2 11 1 1 1 1 1用C++

原文地址: https://www.cveoy.top/t/topic/ihxM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录