Spiral Matrix II (rotation Matrix)

Source: Internet
Author: User

Question prototype:

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 ]]
Basic Ideas:

We noticed that the position of each start operation is the diagonal line. When a circle is printed, the column coordinate is first accumulated 1, then the row coordinate is accumulated 1, and then the column coordinate class is reduced by 1, and the last row coordinate is subtracted by 1. Repeat the preceding operation until the end.

Public int [] [] generateMatrix (int n) {int [] [] num = new int [n] [n]; int layer = 0; // number of layers enclosed by int I = 1; // count int row = 0; int column = 0; while (true) {while (column
 
  
= Layer) {num [row] [column] = I; I ++; column --;} column ++; row --; layer ++; // Add the number of circles to a while (row> = layer) {num [row] [column] = I; I ++; row --;} if (layer> (n + 1)/2) break; // reassign the start row = layer; column = layer;} return num ;}
 



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.