首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

算法經典:順時針螺旋方陣生成(PAT 基礎級 數組-13)

     編輯:關於C語言

題目描述

輸入正整數 N (≤10),輸出 N×N 矩陣,將 1 到 N² 按順時針螺旋順序填入,從左上角開始向右。

邊界收縮法核心思路

維護四個邊界變量:top、bottom、left、right。按「右→下→左→上」四個方向循環填充,每完成一邊就向內收縮對應邊界,直到邊界交錯。

C 語言標準實現

#include <stdio.h>

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

    while (top <= bottom && left <= right) {
        // 向右:頂行
        for (int col = left; col <= right; col++)
            a[top][col] = num++;
        if (++top > bottom) break; // 收縮上邊界,檢查是否結束

        // 向下:右列
        for (int row = top; row <= bottom; row++)
            a[row][right] = num++;
        if (--right < left) break; // 收縮右邊界

        // 向左:底行
        for (int col = right; col >= left; col--)
            a[bottom][col] = num++;
        if (--bottom < top) break; // 收縮下邊界

        // 向上:左列
        for (int row = bottom; row >= top; row--)
            a[row][left] = num++;
        ++left; // 收縮左邊界
    }

    // 輸出
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++)
            printf("%3d", a[i][j]);
        printf("\n");
    }
    return 0;
}

關鍵點解析

  1. 邊界更新順序:每個方向結束後立即更新對應邊界,並檢查是否越界(break),避免重複填充中心元素(奇數 N 時)
  2. 循環條件:top <= bottom && left <= right 確保還有未填充區域
  3. 輸出格式:%3d 保證對齊,適配 1-3 位數字

測試樣例

輸入:4
輸出:
  1  2  3  4
 12 13 14  5
 11 16 15  6
 10  9  8  7

擴展:逆時針/從中心開始等變體

只需調整四個方向的順序及邊界更新邏輯即可。例如逆時針:右→上→左→下,或從中心向外螺旋(需先計算中心坐標)。

Java 參考實現(原作者參考版本)

// 邏輯完全一致,僅語法差異
while (upBound <= downBound && leftBound <= rightBound) {
    for (int j = leftBound; j <= rightBound; j++) res[upBound][j] = num++;
    if (++upBound > downBound) break;
    for (int i = upBound; i <= downBound; i++) res[i][rightBound] = num++;
    if (--rightBound < leftBound) break;
    for (int j = rightBound; j >= leftBound; j--) res[downBound][j] = num++;
    if (--downBound < upBound) break;
    for (int i = downBound; i >= upBound; i--) res[i][leftBound] = num++;
    ++leftBound;
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved