Leetcode: Spiral Matrix II, leetcodespiral

Source: Internet
Author: User

Leetcode: Spiral Matrix II, leetcodespiral

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 ]]

The same processing as Spiral Matrix is even simpler. This is a Matrix. Layers, and then put them into the array in the order of top right and bottom left. Each element is only accessed once, and the time complexity is O (n ^ 2 ).

 1 public class Solution { 2     public int[][] generateMatrix(int n) { 3         int[][] res = new int[n][n]; 4         if (n < 0) return null; 5         int levelNum = n / 2; 6         int count = 1; 7         for (int level=0; level<levelNum; level++) { 8             for (int i=level; i<n-1-level; i++) { 9                 res[level][i] = count++;10             }11             for (int i=level; i<n-1-level; i++) {12                 res[i][n-1-level] = count++;13             }14             for (int i=n-1-level; i>level; i--) {15                 res[n-1-level][i] = count++;16             }17             for (int i=n-1-level; i>level; i--) {18                 res[i][level] = count++;19             }20         }21         if (n % 2 == 1) {22             res[levelNum][levelNum] = count;23         }24         return res;25     }26 }

 


Java program: Problem: input two integers m and n not greater than 10, and output a spiral matrix in the counterclockwise form of m × n. the output number occupies 2 places,

Baidu hi, I am posting code to you ~


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.