首页 > 代码库 > 螺旋矩阵

螺旋矩阵

 

 本题要求将给定的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

 

解题代码:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int cmp(const void *a, const void *b){
  return *((int *)b) - *((int *)a);
}

int set(int* data,int **res,int pos,int srow,int scol,int row,int col){
  int i,j;
  // it need special operation
  if ( col == 1 ){
    for ( i = srow; i < srow + row; i ++ )
      res[i][scol] = data[pos++];
  }
  else{
    for ( i = scol; i < scol + col; i ++ )
      res[srow][i] = data[pos++];
    for ( i = srow + 1; i < srow + row - 1; i ++ )
      res[i][scol+col-1] = data[pos++];
    for ( i = scol+col-1; i >= scol; i -- )
      res[srow+row-1][i] = data[pos++];
    for ( i = srow + row - 2; i > srow; i -- )
      res[i][scol] = data[pos++];
  }
  return pos;
}

void print(int **res,int row, int col){
  int i,j;
  for ( i = 0; i < row; i ++ ){
    printf("%d",res[i][0]);
    for ( j = 1; j < col; j ++ ){
      printf(" %d",res[i][j]);
    }
    printf("\n");
  }
}

void snake(int* data,int r, int c){
  int i,j;
  int** res;
  int pos = 0;
  int row = r,col = c;
  res = (int **)malloc(sizeof(int *)*row);
  for ( i = 0; i < row; i ++ )
    res[i] = (int *)malloc(sizeof(int)*col);
  for ( i = 0; i <= (c-1)/2; i ++ ){
    pos = set(data,res,pos,i,i,row,col);
    row -= 2;
    col -= 2;
  }
  print(res,r,c);
}

int main(){
  int n;
  int row,col;
  int *data;
  int i,j;
  scanf("%d",&n);
  data = (int *)malloc(sizeof(int)*n);
  for ( i = 0; i < n; i ++ )
    scanf("%d",&data[i]);
  // calculate the right row and col
  for ( i = 1; i <= sqrt(n); i ++ )
    if (n % i == 0){
      col = i;
      row = n / col;
    }
  qsort(data,n,sizeof(int),cmp);
  snake(data,row,col);
  return 0;
}

 

螺旋矩阵