PAT甲级1105 Spiral Matrix (25分)|C++实现

一、题目描述

原题链接
在这里插入图片描述

Input Specification:

在这里插入图片描述

​​Output Specification:

For each test case, output the resulting matrix in m lines, each contains n numbers. There must be exactly 1 space between two adjacent numbers, and no extra space at the end of each line.

Sample Input:

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

Sample Output:

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

二、解题思路

模拟题,稍微有点小麻烦,细节比较多。建立一个matrix二维数组存放结果,按照螺旋的方式进行赋值即可,代码并不难懂,画图来看就十分清晰了。

三、AC代码

#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
using namespace std;
const int maxn = 10001;
int matrix[maxn][maxn];
int calCol(int N)   //计算列数
{
  int ans = 1;
  for(int i=1; i*i <= N; i++)
  {
    if(N%i == 0)    ans = i;
  }
  return ans;
}
bool cmp(int a, int b)  //由大到小排序
{return a > b;}
vector<int> store;
int main()
{
  int tmp, N;
  scanf("%d", &N);
  for(int i=0; i<N; i++)
  {
    scanf("%d", &tmp);
    store.push_back(tmp);
  }
  sort(store.begin(), store.end(), cmp);
  int col = calCol(N);
  int row = N/col, round = 0, cnt = 0;
  int ROW = row, COL = col;
  int i, j, k, l;
  while(row > 0 && col > 0)
  {
    for(i=0; i<col-1; i++)  //左上到右上
    {
      matrix[round][round+i] = store[cnt++];
    }
    for(j=0; j<row-1; j++)  //右上到右下
    {
      matrix[round+j][round+i] = store[cnt++];
    }
    for(k=0; k<col-1; k++)  //右下到左下
    {
      matrix[round+j][round+i-k] = store[cnt++];
    }
    for(l=0; l<row-1; l++)  //左下到左上
    {
      if(col != 1)
      	matrix[round+j-l][round+i-k] = store[cnt++];
      else
      {
        matrix[round+j][round+i-k] = store[cnt++];
        break;
      }
    }
    if(row == 1 && col == 1)	matrix[round][round] = store[cnt++];
    row -= 2;   //行数-2
    col -= 2;   //列数-2
    round++;
  }
  for(int i=0; i<ROW; i++)
  {
    for(int j=0; j<COL; j++)
    {
      if(j == 0)	printf("%d", matrix[i][j]);
      else	printf(" %d", matrix[i][j]);
    }
    printf("\n");
  }
  return 0;
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值