螺旋矩阵问题

9 篇文章 0 订阅

题目:给定一个正整数n,生成一个包含1到 n^2 的所有元素,且元素按顺时针顺序螺旋排列的正方形矩阵。

例子:

输入:3         

输出:[[1,2,3],[8,9,4],[7,6,5]]

解题思路:这里使用二维数组,按照螺旋排列顺序插入正整数,排列方向共有4个,分别是从左上到右上、从右上到右下、从右下到左下、从左下到左上,这里需要注意方向变化时,数组下标的处理方式

解题流程:

 

代码如下所示:

#include <iostream>
#include <string.h>
using namespace std;

int main() {
    int n;
    cin >> n;
    int arr[n][n];
    memset(arr, 0, sizeof(int) * n * n);

    int i = 0;
    int j = 0;

    int count = 0;
    int path = 1;

    while(count < n * n) {
        switch (path)
        {
        case 1:    // LeftTop to RightTop
            count++;
            arr[i][j] = count;
            if(count < n * n) {
                if((j + 1 < n) && (arr[i][j+1] == 0)) {
                    j++;
                    path = 1;
                }
                else {
                    i++;
                    path = 2;
                }
            }
            break;
        case 2:    // RightTop to RightDown
            count++;
            arr[i][j] = count;
            if(count < n * n) {
                if((i + 1 < n) && (arr[i+1][j] == 0)) {
                    i++;
                    path = 2;
                }
                else {
                    j--;
                    path = 3;
                }
            }
            break;
        case 3:    // RightDown to LeftDown
            count++;
            arr[i][j] = count;
            if(count < n * n) {
                if((j - 1 >= 0) && (arr[i][j-1] == 0)) {
                    j--;
                    path = 3;
                }
                else {
                    i--;
                    path = 4;
                }
            }
            break;
        case 4:    // LeftDown to LeftTop
            count++;
            arr[i][j] = count;
            if(count < n * n) {
                if((i - 1 >= 0) && (arr[i-1][j] == 0)) {
                    i--;
                    path = 4;
                }
                else {
                    j++;
                    path = 1;
                }
            }
            break;
        }
    }

    cout << "[" ;
    for(int c = 0; c < n; c++) {
        cout << "[" ;
        for(int d = 0; d < n; d++) {
            if(d < n - 1) {                
                cout << arr[c][d] << ",";
            }
            else {                
                cout << arr[c][d];
            }
        }
        if(c < n - 1) {                
            cout << "],";
        }
        else {                
            cout << "]";
        }
    }
    cout << "]" << endl;

    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值