您的位置:首页 > 其它

LeetCode(59)SPiral Matrix II

2015-09-06 18:31 465 查看

题目

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测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: