AcWing 756. 蛇形矩阵

输入两个整数 n 和 m,输出一个 n 行 m 列的矩阵,将数字 1 到 n×m按照回字蛇形填充至矩阵中。

具体矩阵形式可参考样例。

输入格式

输入共一行,包含两个整数 n和 m。

输出格式

输出满足要求的矩阵。

矩阵占 n行,每行包含 m个空格隔开的整数。

数据范围

1≤n,m≤100

输入样例:
3 3
输出样例:
1 2 3
8 9 4
7 6 5

#include <iostream>
using namespace std;

const int N = 110;
int a[N][N];

int main()
{
    int r,c;
    cin >> r >> c;

    int left = 0, right = c - 1;
    int top = 0, bottom = r - 1;
    int k = 1;
    while(left <= right || top <= bottom)
    {
        for(int i = left; i <= right && top <= bottom; i++)//构造最上面一行
        {
            a[top][i] = k++;
        }
        top++;
        for(int i = top; i <= bottom && left <= right; i++)//构造最右侧一列
        {
            a[i][right] = k++;
        }
        right--;
        for(int i = right; i >= left && top <= bottom; i--)//构造最下面一行
        {
            a[bottom][i] = k++;
        }
        bottom--;
        for(int i = bottom; i >= top && left <= right; i--)//构造最左侧一列
        {
            a[i][left] = k++;
        }
        left++;
    }
    for(int i = 0; i < r; i++)
    {
        for(int j = 0; j < c; j++) cout<< a[i][j] << " ";
        cout << endl;
    }
    return 0;
}

#include <iostream>

using namespace std;

const int N = 110;

int n, m;
int q[N][N];

int main()
{
    cin >> n >> m;
    int dx[] = {-1, 0, 1, 0}, dy[] = {0, 1, 0, -1};//偏移量
    int x = 0, y = 0, d = 1;//初始坐标和方向
    for (int i = 1; i <= n * m; i ++ )
    {
        q[x][y] = i;
        int a = x + dx[d], b = y + dy[d];//下一个
        if (a < 0 || a >= n || b < 0 || b >= m || q[a][b])//出界或已走过
        {
            d = (d + 1) % 4;//转方向
            a = x + dx[d], b = y + dy[d];
        }
        x = a, y = b;
    }

    for (int i = 0; i < n; i ++ )
    {
        for (int j = 0; j < m; j ++ )
            cout << q[i][j] << ' ';
        cout << endl;
    }

    return 0;
}

  • 10
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值