【leetcode】Spiral Matrix II (middle)

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

 

思路:

我是直接套用了Spiral Matrix 的代码

class Solution {
public:
    vector<vector<int> > generateMatrix(int n) {
        vector<vector<int>> ans(n, vector<int>(n,0));

        int num = 1;
        for(int i = 0; i < (n + 1) / 2; i++)
        {
            //行 ----->
            for(int j = i; j < n - i; j++)
                ans[i][j] = num++;
            //列 向下
            for(int j = i + 1; j < n - i; j++)
                ans[j][n - 1 - i] = num++;
            //行 <-----------
            if(n - i - 1 <= i) //列号 一定要比向左时的列号小 防止重复
                break;
            for(int j = n - i - 2; j >= i; j--)
                ans[n - i - 1][j] = num++;
            //列 向上
            if(i >= n - 1 - i) //行号 一定要比向下时的行号大 防止重复
                break;
            for(int j = n - i - 2; j >= i + 1; j--)
                ans[j][i] = num++;
        }
        return ans;
    }
};

 

另一种写法的:

class Solution {
    public:
        vector<vector<int> > generateMatrix(int n) {
            vector<vector<int> > ret( n, vector<int>(n) );
            int k = 1, i = 0;
            while( k <= n * n )
            {
                int j = i;
                    // four steps
                while( j < n - i )             // 1. horizonal, left to right
                    ret[i][j++] = k++;
                j = i + 1;
                while( j < n - i )             // 2. vertical, top to bottom
                    ret[j++][n-i-1] = k++;
                j = n - i - 2;
                while( j > i )                  // 3. horizonal, right to left 
                    ret[n-i-1][j--] = k++;
                j = n - i - 1;
                while( j > i )                  // 4. vertical, bottom to  top 
                    ret[j--][i] = k++;
                i++;      // next loop
            }
            return ret;
        }
    };

 

posted @ 2015-03-18 16:07  匡子语  阅读(197)  评论(0编辑  收藏  举报