leetcode Array - helix matrix ver2

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:

输入: 3
输出:
[
 [ 1, 2, 3 ],
 [ 8, 9, 4 ],
 [ 7, 6, 5 ]
]

Problem solutions:
T, B, L, R & lt respectively unscanned boundary matrix.
Initial, T = 0, B = n -1, L = 0, R = n-1; Saowan end until the entire matrix is completed.
First scan line from left to right, the first row of L T R column to column, i.e. nums [T] [L] ~ nums [T] [R]; scanned row by a respective T 1
from top to bottom column scan, the T line to the R column, line B, i.e. nums [T] [R] ~ nums [B] [R]; a scanned, the corresponding R 1 Save
right to left scan line, line B the first column to the R and L columns, i.e. nums [B] [R] ~ nums [B] [L]; scanned line, the corresponding B minus 1
from the bottom to the above scanning line L B of the column The first line T, i.e. nums [B] [L] ~ nums [T] [L]; scanned a corresponding increase in L 1.
Here Insert Picture Description


JAVA code:

class Solution {
    public int[][] generateMatrix(int n) {
        
        /*
        从左到右一行
        从上到下一列
        从右到左一行
        从下到上一列
        */
        int[][] res = new int[n][n];
        int num = 1;
        int l = 0;
        int r= n-1;
        int t = 0;
        int b = n-1;
        int i=0;
        while(num<=n*n){
        //从左到右
        for (i=l; i<=r; i++) res[t][i] = num++; 
        t++;
        //从上到下
        for (i=t; i<=b; i++) res[i][r] = num++;
        r--;
        //从右到左
        for (i=r; i>=l; i--) res[b][i] = num++;
        b--;
        //从下到上
        for (i=b; i>=t; i--) res[i][l] = num++;
        l++;
        }
     return res; 
    }

}
Released nine original articles · won praise 0 · Views 256

Guess you like

Origin blog.csdn.net/powerful_ren/article/details/104621036