【1105】Spiral Matrix (25分)【螺旋矩阵】

简介: 【1105】Spiral Matrix (25分)【螺旋矩阵】【1105】Spiral Matrix (25分)【螺旋矩阵】
#include<iostream>
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#include<algorithm>  
#include<map>
#include<vector>
#include<queue> 
#include<functional>
using namespace std;
//外层for遍历每一包裹的层,内4个for分别为右下左上
int cmp(int a,int b){return a>b;}
int main(){
  int N,m,n,t=0;
  scanf("%d",&N);
  for(n=sqrt((double)N);n>=1;n--){
    if(N%n==0){
      m=N/n;//m行n列
      break;
    }
  }
  vector<int>a(N);//共N个数
  for(int i=0;i<N;i++)
    scanf("%d",&a[i]);
  sort(a.begin(),a.end(),cmp);
  vector<vector<int>>b(m,vector<int>(n));
  int level=m/2+m%2;
  for(int i=0;i<level;i++){
    for(int j=i;j<=n-1-i&&t<=N-1;j++)
      b[i][j]=a[t++];
    for(int j=i+1;j<=m-2-i&&t<=N-1;j++)
      b[j][n-1-i]=a[t++];
    for(int j=n-i-1;j>=i&&t<=N-1;j--)
      b[m-1-i][j]=a[t++];
    for(int j=m-2-i;j>=i+1&&t<=N-1;j--)
      b[j][i]=a[t++];
  }
  for(int i=0;i<m;i++){
    for(int j=0;j<n;j++){
      printf("%d",b[i][j]);
      if(j!= n-1) printf(" ");
    }
    printf("\n");
  }
  system("pause");
  return 0;
}
相关文章
|
8月前
codeforces 289 B. Polo the Penguin and Matrix
题目意思是在n*m的矩阵中,你可以对矩阵中的每个数加或者减d,求最少的操作次数,使得矩阵中所有的元素相同。 虽然在condeforces中被分到了dp一类,但完全可以通过排序,暴力的方法解决。
29 0
|
8月前
|
机器学习/深度学习
poj 2155 Matrix (二维树状数组)
这是楼教主出的二维线段树或者是二维树状数组的题,题意很简单,就是有个n*n的矩阵,初始值都是0,然后给你两个操作,一个是给你左上角和右下角的坐标,把这个长方形的区间所有元素反取反(0变1 1变0),另一个是求某个具体坐标的值。 这里我用了二维的线树状数组,一维树状数组可以解决区间更新和点查询的问题,这里只需要加一维就可以了,代码比较好写,不过开始犯了很多低级的错误。
22 0
|
索引
LeetCode 54. Spiral Matrix
给定m×n个元素的矩阵(m行,n列),以螺旋顺序[顺时针]返回矩阵的所有元素
74 0
LeetCode 54. Spiral Matrix
LeetCode 59. Spiral Matrix II
给定正整数n,以螺旋顺序生成填充有从1到n2的元素的方阵。
73 0
|
Java 索引 Python
Leetcode 54:Spiral Matrix 螺旋矩阵
54:Spiral Matrix 螺旋矩阵 Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
816 0
|
机器学习/深度学习 算法 人工智能
[LeetCode]--59. Spiral Matrix II
Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order. For example, Given n = 3, You should return the following matrix: [ [ 1, 2, 3 ], [ 8, 9
1132 0
|
人工智能
[LeetCode]--54. Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order. For example, Given the following matrix: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9
940 0