"059-spiral Matrix II (Spiral Matrix II)"
"leetcode-Interview algorithm classic-java Implementation" "All topics Directory Index"
Original Question
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:
123894765 ]]
Main Topic
Given an integer n, a n*n matrix is generated, and the 1-n^2 number is used to spiral fill.
Thinking of solving problems
The calculation method is used to calculate the corresponding number for each position.
Code Implementation
Algorithm implementation class
Public class solution { Public int[][]Generatematrix(intN) {int[[] result =New intN [n];intLayerintK for(inti =0; I < n; i++) { for(intj =0; J < N; J + +) {layer = Layer (I, J, N);///current coordinates are several levels away //n * n-layer * The last digit (also the largest) used by the outer layer of the layer the first number used by the current layer where the coordinates are locatedk = n * N-(N-2* Layer) * (N-2* Layer) +1; RESULT[I][J] = k;//(N-2 * layer-1): Four (N-2 * layer-1) is the number of all elements in the layer (x, y) coordinates if(i = = layer) {//Case one, coordinates off the upper boundary nearestRESULT[I][J] = k + J-layer; }Else if(j = = N-layer-1) {//Case two, coordinates closest to right edgeRESULT[I][J] = k + (N-2* Layer-1) + I-layer; }Else if(i = = N-layer-1) {//Condition three, coordinates off the lower boundary nearestRESULT[I][J] = k +3* (N-2* Layer-1)-(J-layer); }Else{//Case three, coordinates closest to left edgeRESULT[I][J] = k +4* (N-2* Layer-1)-(I-layer); } } }returnResult }/** * In a n*n matrix, calculate the number of layers outside the (x, y) coordinates, the coordinates start at 0 * * @param x Horizontal axis * @param y ordinate * @ param n Matrix size * Number of layers outside @return coordinates */ Public int Layer(intXintYintN) {x = x < n-1-X? X:n-1-X;//Calculate the nearest distance from the upper and lower boundary of the horizontaly = y < n-1-Y? Y:n-1-Y;//Calculate the nearest distance from the left and right edges of the ordinate returnx < y? x:y;///Smaller value is the perimeter of the coordinate layer}}
Evaluation Results
Click on the picture, the mouse does not release, drag a position, release after the new window to view the full picture.
Special Instructions
Welcome reprint, Reprint please indicate the source "http://blog.csdn.net/derrantcm/article/details/47164439"
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"Leetcode-Interview algorithm classic-java implementation" "059-spiral Matrix II (Spiral Matrix II)"