您的位置:首页 > 其它

LeetCode59 Spiral Matrix II

2016-09-19 22:16 459 查看
题目:

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: (Medium)

[
[ 1, 2, 3 ],
[ 8, 9, 4 ],
[ 7, 6, 5 ]
]

分析:

跟 Sprial Matrix I处理方式一样,先建立好n * n的数组,然后按照顺时针顺序填入数字即可。

代码:

class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> result(n, vector<int>(n,0));
int rowBegin = 0, rowEnd = n - 1, colBegin = 0, colEnd = n - 1;
int count = 1;
while (rowBegin <= rowEnd && colBegin <= colEnd) {
for (int i = colBegin; i <= colEnd; ++i ) {
result[rowBegin][i] = count;
count++;
}
rowBegin++;
if (rowBegin > rowEnd) {
break;
}
for (int i = rowBegin; i <= rowEnd; ++i) {
result[i][colEnd] = count;
count++;
}
colEnd--;
if (colBegin > colEnd) {
break;
}
for (int i = colEnd; i >= colBegin; --i) {
result[rowEnd][i] = count;
count++;
}
rowEnd--;
if (rowBegin > rowEnd) {
break;
}
for (int i = rowEnd; i>= rowBegin; --i) {
result[i][colBegin] = count;
count++;
}
colBegin++;
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: