首页 > 其他 > 详细

pat乙级1050螺旋矩阵

时间:2018-03-14 17:35:49      阅读:178      评论:0      收藏:0      [点我收藏+]

1、用vector建立二维数组:

1 vector<vector<int>> arr(rows);
2 for (int i = 0; i < rows; i++)
3     arr[i].resize(cols);

或:

1 vector<vector<int>> v(m, vector<int>(n));

2、当数组已初始化但某些下标还未赋值时,此下标对应的变量为NULL(见34行)

代码:

 1 #include <iostream>
 2 #include <vector>
 3 #include <algorithm>
 4 #include <math.h>
 5 using namespace std;
 6 
 7 bool cmp(int a, int b)
 8 {
 9     return a > b;
10 }
11 int main()
12 {
13     int n;
14     cin >> n;
15     vector<int> v(n);
16     for (int i = 0; i < n; i++)
17         cin >> v[i];
18     sort(v.begin(), v.end(), cmp);
19     int s = sqrt(n);
20     while (n % s) s--;
21     int cols = s, rows = n / s;
22     /*
23     vector<vector<int>> arr(rows);
24     for (int i = 0; i < rows; i++)
25         arr[i].resize(cols);
26     */
27     vector<vector<int>> arr(rows, vector<int>(cols));
28     int i = 0, j = 0, t = 0;
29     int direction = 1;
30     while (t < n)
31     {
32         if (direction == 1)
33         {
34             if (j < cols && arr[i][j] == NULL)
35                 arr[i][j++] = v[t++];
36             else
37             {
38                 i++;
39                 j--;
40                 direction = 2;
41             }    
42         }
43         else if (direction == 2)
44         {
45             if (i < rows && arr[i][j] == NULL)
46                 arr[i++][j] = v[t++];
47             else
48             {
49                 j--;
50                 i--;
51                 direction = 3;
52             }
53         }
54         else if (direction == 3)
55         {
56             if (j >= 0 && arr[i][j] == NULL)
57                 arr[i][j--] = v[t++];
58             else
59             {
60                 i--;
61                 j++;
62                 direction = 4;
63             }
64         }
65         else if (direction == 4)
66         {
67             if (i >= 0 && arr[i][j] == NULL)
68                 arr[i--][j] = v[t++];
69             else
70             {
71                 i++;
72                 j++;
73                 direction = 1;
74             }
75         }
76     }
77     for (int i = 0; i < rows; i++)
78     {
79         for (int j = 0; j < cols; j++)
80         {
81             if (j) cout << " ";
82             cout << arr[i][j];
83         }
84         cout << endl;
85     }
86     return 0;
87 }

 

pat乙级1050螺旋矩阵

原文:https://www.cnblogs.com/lxc1910/p/8568797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!