和 Spiral Matrix I用了一个方法,遇到边界和赋过值的地方就拐弯。但是速度比较慢。
class Solution {
public:
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> res(n, vector<int>(n));
if (n == 0) return res;
vector<vector<int>> direct = { { 0, 1 }, { 1, 0 }, { 0, -1 }, { -1, 0 } };
int step =0 ;
int count = 1;
int x = 0;
int y = 0;
res[x][y] = count;
while (count < n*n)
{
while ((x + direct[step][0] >= 0) && (x + direct[step][0] < n) && (y + direct[step][1] >= 0) && (y + direct[step][1] < n) && (res[x + direct[step][0]][y + direct[step][1]] == 0) && (count <= n*n))
{
x = x + direct[step][0];
y = y + direct[step][1];
count++;
res[x][y] = count;
}
step = (step + 1) % 4;
}
return res;
}
};
最快的还是记录步长转圈的:
i记录的是转了第几圈,j是变动的那个坐标。这个方法是找到每一圈长度和圈数的关系。
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;
}
};