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

C++ 環形矩陣填充(螺旋矩陣)實現

     編輯:關於C++

算法思路

按層(圈)填充。每圈四條邊:左邊向下、底邊向右、右邊向上、頂邊向左。圈數 cir = 0, 1, ...,每圈邊長 siz = n - 2*cir。當 siz == 1 時填中心單元。用 map<int, map<int,int>> 或二維 vector 存儲。

代碼

#include <bits/stdc++.h>
using namespace std;
int main() {
    int n;
    while (cin >> n) {
        vector> a(n, vector(n, 0));
        int cnt = 1;
        for (int cir = 0; cir < (n+1)/2; cir++) {
            int siz = n - 2*cir;
            if (siz == 1) { a[cir][cir] = cnt++; break; }
            for (int i = 0; i < siz-1; i++) a[cir+i][cir] = cnt++;          // 左邊向下
            for (int j = 0; j < siz-1; j++) a[cir+siz-1][cir+j] = cnt++;    // 底邊向右
            for (int i = siz-1; i > 0; i--) a[cir+i][cir+siz-1] = cnt++;     // 右邊向上
            for (int j = siz-1; j > 0; j--) a[cir][cir+j] = cnt++;           // 頂邊向左
        }
        for (auto& row : a) {
            for (int x : row) cout << setw(4) << x;
            cout << '\n';
        }
    }
    return 0;
}

示例輸出 (n=5)

   1   2   3   4   5
  16  17  18  19   6
  15  24  25  20   7
  14  23  22  21   8
  13  12  11  10   9
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved