小小程序媛  
得之坦然,失之淡然,顺其自然,争其必然

题目

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

分析

与54题Spiral Matrix相似题,为一个二维矩阵进行螺旋状赋值

AC代码

class Solution {
public:
    vector<vector<int>> generateMatrix(int n) {
        vector<vector<int> > ret(n,vector<int>(n , 0));
        if (n <= 0)
            return ret;

        int index = 1 , row = n-1 , col = n-1;
        for (int x = 0, y = 0; x <= row && y <= col; x++, y++)
        {
            //为矩阵首行赋值
            for (int j = y; j <= col; ++j , index++)
                ret[x][j] = index;

            //为矩阵最右列赋值
            for (int i = x + 1; i <= row; ++i,index++)
                ret[i][col] = index;

            //为矩阵最底行赋值
            for (int j = col - 1; j >= y && x != row; --j, index++)
                ret[row][j] = index;

            //为矩阵最左列赋值
            for (int i = row - 1; i > x && y != col; --i, index++)
                ret[i][y] = index;

            //为内旋子矩阵赋值
            row--;
            col--;

        }//for
        return ret;
    }
};

GitHub测试程序源码

posted on 2015-09-06 18:31  Coding菌  阅读(103)  评论(0编辑  收藏  举报