54. 59. Spiral Matrix

1.

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

For example,
Given the following matrix:

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

You should return [1,2,3,6,9,8,7,4,5].

vector<int> spiralOrder(vector<vector<int>>& matrix) {
vector<int> ans;
int m = matrix.size();
if(m < )
return ans;
int n = matrix[].size(), size = m*n, x1=, x2=m-, y1=, y2=n-, i, j, k=;
while(k < size)
{
for(i=y1; i<=y2; i++)
{
ans.push_back(matrix[x1][i]);
k++;
}
for(i=x1+; i<=x2; i++)
{
ans.push_back(matrix[i][y2]);
k++;
}
for(i=y2-; x2>x1 && i>=y1; i--)
{
ans.push_back(matrix[x2][i]);
k++;
}
for(i=x2-; y2>y1 && i>x1; i--)
{
ans.push_back(matrix[i][y1]);
k++;
}
x1++; x2--; y1++; y2--;
}
return ans;
}

注意:

下面和左面的边,即第三个和第四个for循环,要加条件x2>x1和y2>y1,否则会有重复元素。

2.

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 ]
]
vector<vector<int>> generateMatrix(int n) {
vector<vector<int>> ans(n, vector<int>(n, ));
int size = n*n, x1=, x2=n-, y1=, y2=n-, i, j, k=;
while(k < size)
{
for(i=y1; i<=y2; i++)
ans[x1][i] = ++k;
for(i=x1+; i<=x2; i++)
ans[i][y2] = ++k;
for(i=y2-; x2>x1 && i>=y1; i--)
ans[x2][i] = ++k;
for(i=x2-; y2>y1 && i>x1; i--)
ans[i][y1] = ++k;
x1++; x2--; y1++; y2--;
}
return ans;
}
上一篇:AndroidStudio导入Android-PullToRefresh


下一篇:洛谷 P1273 【有线电视网】