Home > Back-end >  Back to the form number
Back to the form number

Time:03-30

Public class Solution {
/* *
* 2 d array output tool
*
* @ param arr two-dimensional data
* @ param length filling length
*/
The static void print (int [] [] arr, int length) {
For (int [] ints: arr) {
For (int anInt: ints) {
System. The out. Print (getLengthSpace (anInt, length));
}
System.out.println();
}
}

/* *
* a filling space utility class
*
* @ param num element
* @ param length the length of the filling
* @ return after the completion of the element
*/
The static String getLengthSpace (int num, int length) {
The StringBuilder result=new StringBuilder (String. The valueOf (num));
Int size=length - result. Length () + 1;
for (int i=0; i Result. Append (" ");
}
Return the result. The toString ();
}

Public static void main (String [] args) {
Print (fun (100), 5);
}

/* *
* back to form array build
*
* @ param n order
* @ return n order array
*/
Static int [] [] fun (int n) {
Int [] [] arr=new int [n] [n].
Int start=1;
//the current building layer, the default is 0
Int layer=0;
//if n is even traverse n/2, if n is odd number is need to traverse n/2 + 1 times,
for (int i=0; i <(n/2 + n % 2); I++) {
//level to fill right
For (int first=layer; First & lt; N - 1 - layer; First++) {
Arr [layer] [first]=start++;
}
//vertical down filling
For (int second=layer; The second & lt; N - 1 - layer; Second++) {
Arr (second) [n - layer - 1]=start++;
}
//level fill left
For (int third=n - layer - 1; Third & gt; Layer; Third -) {
Arr (third) [n - layer - 1]=start++;
}
//vertical filling
For (int forth=n - layer - 1; Forth & gt; Layer; Forth,) {
Arr [forth] [layer]=start++;
}
//on to the next layer traversal
+ + layer;
}
//when n is odd, the most middle element array cannot be fill in, so manual filling to n * n
If (n % 2!=0) {
Int mid=n & gt;> 1;
Arr/mid/mid=n * n;
}
return arr;
}
}
Why the odd want to traverse a more, before the end of the odd number multiple traverse a won't change the value?
Such as 1 2 3
8 and 9 4
7 June 5 finally only 9, traverse again arr [1] [1] is not to be ascribed to 9, and 10 of the final three?
-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
Copyright statement: this article to CSDN blogger (murraya write code) of the original article, follow the CC BY 4.0 - SA the copyright agreement, reproduced and this statement, please attach the original source link
The original link: https://blog.csdn.net/a2524289/article/details/109065276
  • Related