文章

7

粉丝

0

获赞

33

访问

1.4k

头像
旋转方阵 题解:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int n;
    scanf("%d", &n);
    int a[21][21] = {0};
    int top = 1, bottom = n, left = 1, right = n;
    int val = 1;

    while (top <= bottom && left <= right) {
        // 从上到下填充当前最左列
        for (int i = top; i <= bottom; ++i) {
            a[i][left] = val++;
        }
        ++left;

        // 从左到右填充当前最下行
        for (int j = left; j <= right; ++j) {
            a[bottom][j] = val++;
        }
        --bottom;

        // 从下到上填充当前最右列
        for (int i = bottom; i >= top; --i) {
            a[i][right] = val++;
        }
        --right;

        // 从右到左填充当前最上行
        for (int j = right; j >= left; --j) {
            a[top][j] = val++;
        }
        ++top;
    }

    for (int i = 1; i <= n; ++i) {
        for (int j = 1; j <= n; ++j) {
                printf("%-4d", a[i][j]);    //左对齐,右边补空格
        }
        printf("\n");
...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发