Subject description:
Given a positive integer n, to generate a 1 n2 contains all of the elements, and the element arranged spirally clockwise order square matrix.
Example:
Input: 3
Output:
[
[1, 2, 3],
[8,9, 4],
[7, 6, 5]
]
answer:
Generating a n × n matrix empty mat, and then fill the entire inner circumferential simulation:
the definition of the current left and right upper and lower boundaries l, r, t, b, the initial value of the num = 1, the value of the iteration termination tar = n * n;
if num <when = tar, left to right and top to bottom is always filled left to right order from the lower to the cycle, after each fill:
performing num + = 1: a need to obtain the numerical filled;
update border: after completing e.g. from left to right, the upper boundary t + = 1, corresponding to an upper boundary inward contraction.
Use num <= tar instead l <r || t <b conditions as iteration, to solve the problem when n is odd, the digital center of the matrix can not be filled in an iterative process.
Eventually return to mat.
public class L59 { public static int[][] generateMatrix(int n) { int[][] re = new int[n][n]; int l = 0,t = 0,r = n ,b = n; int index = 1; while(index <= n *n){ for(int i = l;i<r;i++){ re[t][i] = index ++; } t ++; for(int i = t;i<b;i++){ re[i][r-1] = index ++; } r --; for ( int i = r-1;i >= l;i--){ re[b-1][i] = index ++; } b --; for(int i = b-1;i>=t;i--){ re[i][l] = index ++; } l ++; } return re; } public static void main(String[] args) { int[][] re = generateMatrix(3); int s = 0; } }