Leetcode_c++: Spiral Matrix II (059)

Source: Internet
Author: User
Topic

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

For example,
Given n = 3,

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

Complexity: O (NM)

Class Solution {public:vector<vector<int> > Generatematrix (int n) {if (n==0) return vector<ve Ctor<int> > ();

        Returns an empty array of vector<vector<int> > Ret (n,vector<int> (n,0));
        int rowbegin=0;
        int rowend=n-1;
        int colbegin=0;
        int colend=n-1;

        int num=1;
                while (rowbegin<=rowend && colbegin <= colend) {if (num<=n*n)//To determine whether the maximum value is reached {
                    Traverse to the right to add a for (int j=colbegin;j<=colend;j++) {ret[rowbegin][j]=num;
                num++;

            }} rowbegin++;
                    if (num<=n*n)//To determine whether the maximum is reached {///down traversal add for (int i=rowbegin;i<=rowend;i++) {
                    Ret[i][colend]=num;
                num++;


            }} colend--;
                if (num<=n*n)//To determine whether the maximum value is reached {Walk to the left to add for (int j=colend;j>=colbegin;j--) {ret[rowend][j]=num;
                num++;

            }} rowend--;
                    if (num<=n*n)//To determine whether the maximum is reached {///Up traversal add for (int i=rowend;i>=rowbegin;i--) {
                    Ret[i][colbegin]=num;
                num++;


        }} colbegin++;
    return ret; }
};

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.