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 ~