ACwing756サーペンタインマトリックス

タイトル説明

2つの整数nとmを入力し、n行とm列の行列を出力し、行列に1からn * mまでの数字を蛇行した形で塗りつぶします。

特定のマトリックス形式は、サンプルを参照できます。

入力フォーマット

2つの整数nとmを含む行を入力します。

出力フォーマット

要件を満たすマトリックスを出力します。

行列はn行を占め、各行にはスペースで区切られたm個の整数が含まれます。

データ範囲

1≤n、m≤1001≤n、m≤100

入力サンプル:

3 3

サンプル出力:

1 2 3
8 9 4
7 6 5

進行方向(右下と左上)に応じて、歩いていない場所に値を割り当てます 

#include <iostream>
#include <cstdio>

using namespace std;
const int MAX = 109;

int a[MAX][MAX];


int main()
{
    int n, m;

    scanf("%d%d", &n, &m);

    int sum = n * m;

    int cnt = 0;
    int row = 0;
    int col = 0;
    while(cnt < sum)
    {
        for(int i = 0; i < m; i++) // 右走
        {
            if(!a[row][i])
            {
                a[row][i] = ++ cnt;
                col = i;
            }

        }


        for(int i = row + 1; i < n; i++) // 下走
        {
            if(!a[i][col])
            {
                a[i][col] = ++cnt;
                row = i;
            }
        }

        for(int i = col - 1; i >= 0; i--) // 左走
        {
            if(!a[row][i])
            {
                a[row][i] = ++cnt;
                col = i;
            }
        }

        for(int i = row - 1; i >= 0; i--)
        {
            if(!a[i][col])
            {
                a[i][col] = ++cnt;
                row = i;
            }
        }
    }

    for(int i = 0; i < n; i++)
    {
        for(int j = 0; j < m; j++)
            printf("%d ", a[i][j]);
        printf("\n");
    }

    return 0;
}

 

 

おすすめ

転載: blog.csdn.net/weixin_44620183/article/details/112892998