LeetCode:M59. Spiral Matrix II

来源:互联网 发布:淘宝客返利怎么设置 编辑:程序博客网 时间:2024/06/05 17: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 ]]
//TC=O(n^2)public class Solution {    public int[][] generateMatrix(int n) {        //special case        if(n==0) return new int[0][0];                int[][] res = new int[n][n];        int num = 1;        int top=0, right=n-1, bottom=n-1, left=0;        while(top<bottom){                        //上边框            for(int i=left; i<right; i++){                res[top][i]=num;                num++;            }                        //右边框            for(int i=top; i<bottom; i++){                res[i][right]=num;                num++;            }                        //下边框            for(int i=right; i>left; i--){                res[bottom][i]=num;                num++;            }                        //左边框            for(int i=bottom; i>top; i--){                res[i][left]=num;                num++;            }                          //这里容易遗漏            top++;            right--;            bottom--;            left++;        }        //when top=bottom, it comes to the center        if(num==n*n)            res[top][top]=num;                return res;    }}





原创粉丝点击