LeetCode -- Spiral Matrix II

Source: Internet
Author: User

LeetCode -- Spiral Matrix II
Description:


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


For example,
Given n = 3,


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


Given a number, the matrix is generated from the external to the internal.


Ideas:


This topic is mainly to complete a rotating process. The width of the track cycle is divided into four different directions: left-to-right, top-to-bottom, right-to-left, and left-to-top. Cycle decreases every time.
Pay attention to the difference in cycle values where n is an odd and even number.




Implementation Code:

public class Solution {    public int[,] GenerateMatrix(int n) {        var matrix = new int[n,n];    var row = n % 2 == 0 ? n / 2 : (n+1) / 2;    var count = 1;    for(var cycle = 0;cycle < row; cycle++){        // left to right    for(var col = cycle;col < n - cycle - 1; col++){    matrix[cycle,col] = count ++;    }        // right to bottom    for(var r = cycle ; r < n - cycle; r++){    matrix[r, n - cycle - 1] = count ++;    }        // bottom to left    for(var col = n - cycle - 2;col >= cycle; col --){    matrix[n-cycle-1,col] = count ++;    }        // left to top    for(var r = n - cycle - 2;r > cycle; r --){    matrix[r,cycle] = count ++;    }    }        return matrix;    }}


 

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.