Title:
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]]
Test Instructions:
given an integer n, generates a square matrix. The matrix contains from 1 to n 2 These elements, and is arranged in a spiral order.
For example, given n = 3
,
You should return the following matrix:
[[1, 2, 3], [8, 9, 4], [7, 6, 5]]
Algorithm Analysis:
Similar to the title "Spiral Matrix", the spiral-shaped placement, to go to the good.
The final case here is that the matrix shape in the "Spiral matrix" is not necessarily a square, so going to the last remaining element might be one or one column or row.
The resulting square matrix is clearly stated in the subject, so the final remaining element is only possible for one, and the code considers this to be OK.
AC Code:
public class Solution {public int[][] Generatematrix (int n) {int startX = 0; int starty = 0; int endx = n-1; int EndY = n-1; int[][] Matrix = new Int[n][n]; int startvalue = 1; while (StartX <= endx) {startvalue = Fillnumber (StartX, Starty, EndX, EndY, Matrix, startvalue); startx++;//outer ring traverse, traverse inner ring starty++; endx--; endy--; } return matrix; } public int Fillnumber (int startX, int starty, int endx, int endY, int[][] matrix, int startv) {if (STA RtX = = EndX) {Matrix[startx][starty] = StarTV; return-1; } for (int i = starty; I <= EndY; i++)//From left to right {matrix[startx][i] = StarTV; startv++; } for (int i = StartX + 1; I <= endx; i++)//top-down {Matrix[i][endy] = StarTV; startv++; } for (INT i = endY-1; I >= starty; i--)//from right and left {matrix[endx][i] = StarTV; startv++; } for (int i = endX-1; I >= StartX + 1; i--)//Bottom up {matrix[i][starty] = StarTV; startv++; } return STARTV; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Spiral Matrix II