【PAT (Basic Level) Practice (中文)】1050 螺旋矩阵 (25 分)题解

本题要求将给定的 N 个正整数按非递增的顺序,填入“螺旋矩阵”。所谓“螺旋矩阵”,是指从左上角第 1 个格子开始,按顺时针螺旋方向填充。要求矩阵的规模为 m 行 n 列,满足条件:m×n 等于 N;m≥n;且 m−n 取所有可能值中的最小值。

输入格式:

输入在第 1 行中给出一个正整数 N,第 2 行给出 N 个待填充的正整数。所有数字不超过 104,相邻数字以空格分隔。

输出格式:

输出螺旋矩阵。每行 n 个数字,共 m 行。相邻数字以 1 个空格分隔,行末不得有多余空格。

输入样例:

12
37 76 20 98 76 42 53 95 60 81 58 93

结尾无空行

输出样例:

98 95 93
42 37 81
53 20 76
58 60 76

结尾无空行

思路:

1.得到m和n的思路:先找n,让n从1开始遍历知道m < n。这个过程中用min记录m-n的最小值

最后得到适合的m和n,其中m = N/n

2.螺旋排布的思路:

定义一个方向变量,当direction = 1时向右走,direction = 2 时向下走,direction = 3 时向左走,direction = 4时向上走。然后如果走的时候碰到了矩阵边缘也就是x和y离开数组的范围,或者正在经历的方向上的数字已经被改写了,那就改变方向

最后输出矩阵。

易错测试点:

1

1

#include <iostream>
#include <algorithm>
using namespace std;

bool cmp(int a,int b)
{
    return a>b;
}
void chai(int N,int *p1,int *p2)
{
    int min = N;
    for (int n = 1;(double)N/n >= n;n++)
    {
        if (N%n == 0 && N/n-n <= min)
        {
            *p1 = N/n;
            *p2 = n;
            min = N/n-n;
        }
    }
}
int main()
{
    int N,m,n,x = 0,y = 0,direction = 1;
    cin >> N;
    int num1[N];
    chai(N,&m,&n);
    int num2[m][n];
    for (int i = 0;i < m;i++)
    {
        for (int j = 0;j < n;j++)
        {
            num2[i][j] = 0;
        }
    }
    for (int i = 0;i < N;i++) cin >> num1[i];
    sort(num1,num1+N,cmp);
    num2[0][0] = num1[0];
    for (int i = 1;i < N;i++)
    {
        if (x - 1 >= 0 && direction == 4)
        {
            if (num2[x-1][y]) direction = 1;
        }
        else if (direction == 4) direction = 1;
        if (y + 1 < n && direction == 1)
        {
            if (num2[x][y+1]) direction = 2;
        }
        else if (direction == 1) direction = 2;
        if (x + 1 < m && direction == 2)
        {
            if (num2[x+1][y]) direction = 3;
        }
        else if (direction == 2) direction = 3;
        if (y - 1 >= 0 && direction == 3)
        {
            if (num2[x][y-1]) direction = 4;
        }
        else if (direction == 3) direction = 4;
        switch(direction)
        {
            case 1:
                y += 1;
                break;
            case 2:
                x += 1;
                break;
            case 3:
                y -= 1;
                break;
            case 4:
                x -= 1;
                break;
        }
        num2[x][y] = num1[i];
    }
    for (int i = 0;i < m;i++)
    {
        for (int j = 0;j < n;j++)
        {
            if (j == n-1) cout << num2[i][j] << endl;
            else cout << num2[i][j] << " ";
        }
    }
    return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值