# Leetcode--spiral Matrix II

Source: Internet
Author: User

Given an integer n, generate a square matrix filled with elements from 1 to n2 in spiral order.

For example,
Given N = `3` ,

You should return the following matrix:
`[[1, 2, 3], [8, 9, 4], [7, 6, 5]]`
Solution

`Class Solution {public:vector<vector<int> > Generatematrix (int n) {vector<vector<int>        > res;            for (int i=0; i<n; i++) {vector<int> temp (n,0);        Res.push_back (temp);        } bool left_up = true;        BOOL Left_down = false;        BOOL right_up = false;        BOOL Right_down = false;        int min_i = 0;        int max_i = n-1;        int min_j = 0;        int max_j = n-1;        int count = 1; while (min_i<=max_i && min_j<=max_j) {if (left_up = = True) {for ( int j = Min_j; j<=max_j;                    J + +) {Res[min_i][j] = count;                count++;                } left_up = false;                Right_up = true;            Min_i = min_i+1;                   } else if (right_up = = True) {for (int i=min_i; i<=max_i; i++) { Res[i][max_j] = count;                count++;                } Max_j = max_j-1;                Right_up = false;            Right_down = true;                    } else if (Right_down = = True) {for (int j=max_j; j>=min_j; j--) {                    RES[MAX_I][J] = count;                count++;                } max_i = max_i-1;                Left_down = true;            Right_down = false; } else {for (int i=max_i; i>=min_i; i--) {res[i                    ][min_j] = count;                count++;                } Min_j = min_j+1;                Left_up = true;            Left_down = false;    }} return res; }};`

Leetcode--spiral Matrix II

Related Keywords:

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.