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
定义四个方向,沿着一个方向一直走到尽头,走不动了就换方向继续走

类似题目: LeetCode 54. 螺旋矩阵   
#include<iostream>
using namespace std;

int res[110][110];

int dx[] = {0,1,0,-1};
int dy[] = {1,0,-1,0};

int main(){
    int n,m;
    cin>>n>>m;
    int x = 0,y = -1,step = 0;
    for(int i = 1; i <= n * m; ++i){
        if (x + dx[step] < 0 || x + dx[step] >= n || y + dy[step]< 0 || y + dy[step] >= m || res[x + dx[step]][y + dy[step]])
            step = (step + 1) % 4;
        x += dx[step];
        y += dy[step];
        res[x][y] = i;
    }
    
    for (int i = 0; i < n; ++i){
        for (int j = 0; j < m; ++j)
        cout<<res[i][j]<<" ";
        cout<<endl;
    }            
    
    return 0;
}
发布了423 篇原创文章 · 获赞 38 · 访问量 4万+

猜你喜欢

转载自blog.csdn.net/weixin_41514525/article/details/104889594