Print the spiral matrix as required:
The length of the input side. The output style is as follows:
Summary rules:
It can be seen that the rotation direction is: Right, bottom, left, top;
Number of times: Right, bottom,; left, top, right, right, bottom, bottom, left, left, top, up ...... The number of output times (rotation radius) increases by 1 every two times.
With these rules, we can summarize and use them.
(PS: Pay attention to the usage of container adapter Queue)
# Include <iostream> # include <queue> # include <utility> using namespace STD; queue <pair <int, int> mov; int A [100] [100]; // move the direction to the container adapter queue; void intialqueue () {mov. push (make_pair (0, 1); // rightmov. push (make_pair (1, 0); // downmov. push (make_pair (0,-1); // leftmov. push (make_pair (-1, 0); // up} void printmat (INT s) {int sum = S * s; int x = (S-1)/2, y = (S-1)/2; // pay attention to the starting position. Otherwise, an even side length output is zero. A [x] [Y] = 1; int current = 2; if (current> sum) return; int radius = 1, addradius = 1; // radius: The side length of each rotation; addradius: The side length increments; pair <int, int> TMP; while (1) {for (INT I = 0; I <radius & Counter T <= sum; I ++) // current <= sum note: "<=" {x + = mov. front (). first; y + = mov. front (). second; A [x] [Y] = current; current ++;} If (current> sum) return; // update the radius length every two steps; addradius = (addradius + 1) % 2; radius + = addradius; TMP = mov. front (); MoV. pop (); MoV. push (TMP) ;}} int main () {int N; CIN >>n; intialqueue (); printmat (n); For (INT I = 0; I <N; I ++) {for (Int J = 0; j <n; j ++) {if (a [I] [J] <10) cout <""; // align; cout <A [I] [J] <"" ;}cout <Endl ;}}