leetcode 81: Spiral Matrix II

来源:互联网 发布:python的readline 编辑:程序博客网 时间:2024/05/18 15:05
Spiral Matrix IIMar 28 '12

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 ]]

 

 

public class Solution {    public int[][] generateMatrix(int n) {        // Start typing your Java solution below        // DO NOT write main() function                int[][] res = new int[n][n];        if(n<1) return res;                int top=0, bottom=n-1, left=0, right=n-1;                int loop = (n+1)/2;                for(int i=0, seq=1; i<loop; i++) {                        for(int j=left; j<=right; j++) {                res[top][j] = seq++;            }            top++;                        if(top>bottom) return res;            for(int j=top; j<=bottom; j++) {                res[j][right] = seq++;            }            right--;                        if(left>right) return res;            for(int j=right; j>=left; j--) {                res[bottom][j] = seq++;            }            bottom--;                        if(top>bottom) return res;            for(int j=bottom; j>=top; j--) {                res[j][left] = seq++;            }            left++;        }                return res;    }}


 

class Solution {public:    vector<vector<int> > generateMatrix(int n) {        // IMPORTANT: Please reset any member data you declared, as        // the same Solution instance will be reused for each test case.                vector<int> element(n, 0);        vector<vector<int> > matrix(n, element);        int lb = 0, rb = n-1, ub = 0, bb = n-1;                for(int i=1; i<=n*n; ) {            //up bound            for(int i1=lb; i1<=rb; i1++) {                matrix[ub][i1] = i++;            }            ++ub;            if(i>n*n) return matrix;            for(int i2=ub; i2<=bb; i2++) {                matrix[i2][rb] = i++;            }                --rb;            if(i>n*n) return matrix;            for(int i3=rb; i3>=lb; i3--) {                matrix[bb][i3] = i++;            }                --bb;            if(i>n*n) return matrix;            for(int i4=bb; i4>=ub; i4--) {                matrix[i4][lb] = i++;            }                ++lb;        }                return matrix;    }};

原创粉丝点击