思路同 756. 蛇形矩阵,模拟法,设定边界。
小知识: ++ k
要比 k ++
快一点,因为 ++ k
返回的是一个引用,而 k ++
会产生一个临时对象,返回的是一个对象,效率降低。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> matrix(n, vector<int>(n));
int k = 0;
int left = 0, right = n - 1, top = 0, bottom = n - 1;
while (true)
{
for (int i = left; i <= right; ++ i) matrix[top][i] = ++ k;
if ( ++ top > bottom) break;
for (int i = top; i <= bottom; ++ i) matrix[i][right] = ++ k;
if ( -- right < left) break;
for (int i = right; i >= left; -- i) matrix[bottom][i] = ++ k;
if ( -- bottom < top) break;
for (int i = bottom; i >= top; -- i) matrix[i][left] = ++ k;
if ( ++ left > right) break;
}
return matrix;
}
};