天天看點

平方矩陣

acwing753題:平方矩陣 I

輸入整數N,輸出一個N階的回字形二維數組。

數組的最外層為1,次外層為2,以此類推。

輸入格式

輸入包含多行,每行包含一個整數N。

當輸入行為N=0時,表示輸入結束,且該行無需作任何處理。

輸出格式

對于每個輸入整數N,輸出一個滿足要求的N階二維數組。

每個數組占N行,每行包含N個用空格隔開的整數。

每個數組輸出完畢後,輸出一個空行。

資料範圍

0≤N≤100

輸入樣例:

1

2

3

4

5

輸出樣例:

1

1 1

1 1

1 1 1

1 2 1

1 1 1

1 1 1 1

1 2 2 1

1 2 2 1

1 1 1 1

1 1 1 1 1

1 2 2 2 1

1 2 3 2 1

1 2 2 2 1

1 1 1 1 1

#include <bits/stdc++.h>
using namespace std;

int main(void)
{
    int n;
    while(cin>>n&&n!=0)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                int up=i,down=n-i+1,left=j,right=n-j+1;
                cout<<min(min(up,down),min(left,right))<<" ";
            }
            cout<<endl;
        }
        cout<<endl;
    }
    return 0;
}
           

acwing754題:平方矩陣 II

輸入整數N,輸出一個N階的二維數組。

數組的形式參照樣例。

輸入格式

輸入包含多行,每行包含一個整數N。

當輸入行為N=0時,表示輸入結束,且該行無需作任何處理。

輸出格式

對于每個輸入整數N,輸出一個滿足要求的N階二維數組。

每個數組占N行,每行包含N個用空格隔開的整數。

每個數組輸出完畢後,輸出一個空行。

資料範圍

0≤N≤100

輸入樣例:

1

2

3

4

5

輸出樣例:

1

1 2

2 1

1 2 3

2 1 2

3 2 1

1 2 3 4

2 1 2 3

3 2 1 2

4 3 2 1

1 2 3 4 5

2 1 2 3 4

3 2 1 2 3

4 3 2 1 2

5 4 3 2 1

//方法1
#include <bits/stdc++.h>
using namespace std;

int main(void)
{
    int n;
    while(cin>>n&&n!=0)
    {
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=n;j++)
            {
                cout<<abs(i-j)+1<<" ";
            }
            cout<<endl;
        }
        cout<<endl;
    }
    return 0;
}


//方法2
#include <bits/stdc++.h>

using namespace std;

int q[110][110];

int main(void)
{
    int n;
    while (cin >> n&&n!=0)
    {
        for (int i = 0; i < n; i ++ )
        {
            q[i][i] = 1;
            for (int j = i + 1, k = 2; j < n; j ++, k ++ ) q[i][j] = k;
            for (int j = i + 1, k = 2; j < n; j ++, k ++ ) q[j][i] = k;
        }

        for (int i = 0; i < n; i ++ )
        {
            for (int j = 0; j < n; j ++ ) cout << q[i][j] << ' ';
            cout << endl;
        }
        cout << endl;
    }
    return 0;
}
           
如有問題,歡迎在評論區提問

繼續閱讀