码迷,mamicode.com
首页 > 其他好文 > 详细

1050. 螺旋矩阵(25)

时间:2017-03-19 17:24:15      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:ring   namespace   string   names   else   格式   正整数   include   scan   

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
#include <iostream>
#include <iomanip>
#include <math.h>
#include <stdio.h>
#include <string>
#include <cstring>
#include <cstdio>
#include <algorithm>
#include <vector>

using namespace std;

bool comp(int a, int b)
{
    return a > b;
}

int main()
{
    int N;
    scanf("%d", &N);
    int a[N];
    for (int i = 0; i<N; i++) {
        scanf("%d", &a[i]);
    }
    sort(a, a+N, comp);
    int row = ceil(sqrt(N));
    while (N%row != 0)
    {
        row++;//ROW即为从SQRT开始的最小的能整数N的整数
    }
    int col = N / row;

    int b[row][col];
    for (int i = 0; i<row; i++) {
        for (int j = 0; j<col; j++) {
            b[i][j] = 0;
        }
    } // 二维数组初始化 

    int i = 0, j = 0;
    int count = 0;
    while (count != N) {
        for (; j<col; j++) {
            if (!b[i][j]) {
                b[i][j] = a[count++];
            }
            else {
                break;
            }
        } // 向右走 
        j--; // 退出不满足的列 
        i++; // 进入下一行 
        for (; i<row; i++) {
            if (!b[i][j]) {
                b[i][j] = a[count++];
            }
            else {
                break;
            }
        } // 向下走 
        i--; // 退出不满足的行 
        j--; // 进入下一列 (向左) 
        for (; j >= 0; j--) {
            if (!b[i][j]) {
                b[i][j] = a[count++];
            }
            else {
                break;
            }
        } // 向左走 
        i--; // 进入下一行 (向上) 
        j++; // 退出不满足的列 
        for (; i >= 0; i--) {
            if (!b[i][j]) {
                b[i][j] = a[count++];
            }
            else {
                break;
            }
        } // 向上走 
        i++; // 退出不满足的行(下一步向右) 
        j++; // 进入下一列(向右)                               
    }

    for (int i = 0; i<row; i++) {
        for (int j = 0; j<col; j++) {
            printf("%d", b[i][j]);
            if (j < col - 1) {
                printf(" ");
            }
        }
        printf("\n");
    }

    system("pause");
    return 0;
}

 

1050. 螺旋矩阵(25)

标签:ring   namespace   string   names   else   格式   正整数   include   scan   

原文地址:http://www.cnblogs.com/brightz2017/p/6580664.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!