# PAT Advanced 1105 Spiral Matrix

## Overview

PAT advanced 1105 Spiral Matrix can be solved by first sorting the numbers and then recursively print the sorted list in the spiral matrix.

## PAT Advenced 1105 Spiral Matrix Problem

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 104. 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
```

## PAT Advenced 1105 Spiral Matrix Algorithm

This problem tests 3 aspects:

1. sorting, this is easy, using STL
2. figure out the row and columns such that row * column == n and row >= clumn, this is math problem
3. two dimentional array index manupilation, that is, map the elements from one dimensional vector into a two dimensional array by spiral order (clockwise). It is easier to understand and achive the solution recursively, essentially, we need 4 print, print it into the top row, print the numbers in the right column, print the numbers in the bottom row, print the numbers in the left column, and then the problem is reduced into the same 4 pass printing with a smaller number of rows and columns.

The following C++ code is accepted by PAT OJ to pass this 1105 Spiral matrix using the algorithm above:

I wrote a post of solving a similar spiral matrix problem before: Spiral Matrix I and II: Recursive and Iterative Index Calculation.

Be careful about the cases where the resulted matrix has only 1 column or row, and the cases where the number of rows equal to the number of columns, make sure the caclulation of the rows and columns are correct, test with n = 0, 1, 2, 3, 4.

## Summary

I have given recurisve algorithm, test cases, and related problem references in this post to solve PAT Advanced 1105 Spiral Matrix.

Written on June 19, 2016