[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,生成一个方阵,它含有从1到n^2的元素,而且这些整数以向中间旋转的方式排列。
我采用的是最笨的办法,先来看外面一圈是如何计算的,第0行,从0~2依次是1~3,然后是第2列,第1个是4,然后是第2行,从2~0依次是5~7,然后是第0列,第1个是8。
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> > vec(n, vector<int>(n));
        
        int i = 0, j = 0;
        int count = 1;
        int index = 0;
        int start = 0, end = n-1;
        while(count <= n*n) {
            for(i = index, j = start; j <= end && count <= n*n; j++)
                vec[i][j] = count++;

            for(j = n-1-index, i = start+1; i < end && count <= n*n; i++)
                vec[i][j] = count++;
 
            for(i = n-1-index, j = end; j >= start && count <= n*n; j--)
                vec[i][j] = count++;
 
            for(j = index, i = end-1; i >= start+1 && count <= n*n; i--)
                vec[i][j] = count++;

            index++;
            start++;
            end--;
        }

        return vec;  
    }
};


posted @ 2013-10-29 21:46  pangbangb  阅读(119)  评论(0编辑  收藏  举报