1105 Spiral Matrix

This time your job is to fill a sequence of N positive integers into a spiral matrix in non-increasing order. A spiral matrix is filled in from the first element at the upper-left corner, then move in a clockwise spiral. The matrix has m rows and n columns, where m and n satisfy the following: m×n must be equal to N; m≥n; and m−n is the minimum of all the possible values.

Input Specification:

Each input file contains one test case. For each case, the first line gives a positive integer N. Then the next line contains N positive integers to be filled into the spiral matrix. All the numbers are no more than 1. The numbers in a line are separated by spaces.

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

题意:

  给出一个数组,按照降序,在一个martix中顺时针螺旋排列,要求row >= col 且 abs(row - col)最小。

思路:

  用一个visited[]数组标记martix是否已经遍历过,然后再按照dirs[]数组进行右下左上,循环填入即可。

Code:

 1 #include <bits/stdc++.h>
 2 
 3 using namespace std;
 4 
 5 int main() {
 6     int n;
 7     cin >> n;
 8     vector<int> v(n);
 9     for (int i = 0; i < n; ++i) cin >> v[i];
10     sort(v.begin(), v.end(), [](int x, int y) -> bool { return x > y; });
11     int mid = sqrt(n) + 1;
12     int row, col;
13     for (int i = mid; i >= 1; --i) {
14         if (n % i == 0) {
15             row = i;
16             col = n / i;
17             break;
18         }
19     }
20     if (row < col) {
21         int temp = row;
22         row = col;
23         col = temp;
24     }
25     vector<vector<int> > matrix(row, vector<int>(col, 0));
26     vector<vector<int> > visited = matrix;
27     int posX = 0, posY = -1, i = 0;
28     int dirs[5] = {0, 1, 0, -1, 0};
29     while (i < n) {
30         for (int j = 0; j < 4; ++j) {
31             while (i < n) {
32                 int curX = posX + dirs[j];
33                 int curY = posY + dirs[j + 1];
34                 if (curX >= 0 && curX < row && curY >= 0 && curY < col &&
35                     visited[curX][curY] == 0) {
36                     visited[curX][curY] = 1;
37                     posX = curX;
38                     posY = curY;
39                     matrix[posX][posY] = v[i];
40                     ++i;
41                 } else
42                     break;
43             }
44         }
45     }
46     for (int i = 0; i < row; ++i) {
47         cout << matrix[i][0];
48         for (int j = 1; j < col; ++j) {
49             cout << " " << matrix[i][j];
50         }
51         cout << endl;
52     }
53     return 0;
54 }

 

posted @ 2020-04-27 23:22  Veritas_des_Liberty  阅读(154)  评论(0编辑  收藏  举报