59. Spiral Matrix II

来源:互联网 发布:淘宝没有品牌无法发布 编辑:程序博客网 时间:2024/05/01 22:31

题目: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 ]]

类似剥洋葱
    类似于剥洋葱,一圈一圈的写入。设置4个指针,分别是left、right、top、bottom,先写最外圈 第一行->右竖列->最下行->左竖列,然后写倒数第二圈……
public class Solution {    /**     * 简化为剥洋葱的模式,一层一层的剥开     */    public int[][] generateMatrix(int n) {        int[][]a=new int[n][n];        if(n==0) return a;        int left=0,top=0,right=n-1,bottom=n-1;        int cur=1;        while(left<=right && top<=bottom){            for(int i=left;i<=right;i++){                a[top][i]=cur++;            }            for(int i=top+1;i<=bottom;i++){                a[i][right]=cur++;            }            for(int i=right-1;i>=left;i--){                a[bottom][i]=cur++;            }            for(int i=bottom-1;i>top;i--){                a[i][left]=cur++;            }            left++;            top++;            right--;            bottom--;        }        return a;    }}




0 0