PAT 1105

题目 : Spiral Matrix

分值 : 25
难度 : 中等题
思路 : 旋转矩阵,感觉自己太弱了,一开始拿到,各种想歪,还他妈想去找一个依据m n排序的方法
       其实只要模拟遍历就好了,定义边界,每次一个动作之后边界变化就好了。
坑点 : 当输入只有1个数字时,计算M*N如果取不到 sqrt(N)就会出现错误。

具体代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <iostream>
#include <algorithm>
#include <math.h>
using namespace std;
bool cmp(int a ,int b)
{
return a > b;
}
int N ;
int data[100000];
int m , n ;
int main() {
cin >> N ;
for(int i = 0 ; i< N ; i++)
cin >> data[i] ;
for(int i = 1; i <= sqrt(N); i++ )
{
if( N%i == 0) //整除
n = i ;
}
m = N/n ;
//cout << m << " "<<n ;
sort(data,data+N ,cmp) ;
int array[m][n] ;
int xmin= 0 ,xmax = n-1 ;
int ymin= 0 ,ymax = m-1 ;
int x= 0 ,y= 0 ;
int cur = 0 ;

while(cur!=N)
{
for(x =xmin ,y = ymin ; x<=xmax ;x++)
{
array[y][x] = data[cur++] ;
}
ymin ++ ;
for(x =xmax ,y = ymin ; y<=ymax ; ++y)
{
array[y][x] = data[cur++] ;
}
xmax -- ;
if (cur >= N ) { //数据可能已经完成了填充
break;
}
for(x =xmax ,y = ymax ; x>=xmin ; --x)
{
array[y][x] = data[cur++] ;
}
ymax -- ;
for(x =xmin ,y = ymax ; y>=ymin ; --y)
{
array[y][x] = data[cur++] ;
}
xmin++ ;

}
for(int i = 0 ; i < m ; i++)
{
for(int j = 0 ; j< n ; j++)
{
if(j) cout <<" ";
cout << array[i][j] ;
}
cout <<endl ;
}
// cout << N/n <<" "<< n <<endl ;
}