One question per day (3) -- print a spiral matrix (Queue)

Source: Internet
Author: User

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 ;}}

 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.