LeetCode-Spiral Matrix II

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

n,n-1,n-1,n-2,n-2......,2,2,1,1
class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        vector<vector<int> >ret;
        if(n==0)return ret;
        ret.resize(n);
        for(int i=0;i<n;i++)ret[i].resize(n);
        int val=1;
        int x=n-1;
        int y=0;
        int toward=1;// 0 right 1 down 2 left  3 up
        for(int i=0;i<n;i++,val++){
            ret[0][i]=val;
        }
        for(int i=1;i<n;i++){
            for(int k=0;k<2;k++){
                for(int j=i;j<n;j++){
                    switch(toward){
                        case 0:
                        x++;
                        break;
                        case 1:
                        y++;
                        break;
                        case 2:
                        x--;
                        break;
                        case 3:
                        y--;
                        break;
                        default:
                        break;
                    }
                    ret[y][x]=val;
                    val++;
                }
                toward++;
                toward=toward%4;
            }
        }
        return ret;
    }
};
View Code

 

posted @ 2013-10-05 22:55  懒猫欣  阅读(133)  评论(0编辑  收藏  举报