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]
.
1.vector<vector <int> > matrix如何求矩阵的m和n
m = matrix.size();
n = matrix[0].size();
接下来就可以先从左到右,从上到下,从右到左,从下到上了。
4个for循环搞掂。
2.leetcode为什么总是报runtime error?
据说是因为数组越界,除0,爆栈,访问空地址
写这个程序的时候方法和别人的一样,我用了4个for循环,但是runtime error并不是因为时间复杂度过大,时间复杂度太大报的是timeout之类的
在电脑上各种用例反复测试就是没问题,那到底是为什么,因为我定义的变量太多了,我把定义的那些变量删去后就accept了。
前后对比如下:仅仅是因为前面多了个求m和n的取值,难道这是爆栈?
class Solution{
public:
vector<int> spiralOrder(vector<vector<int> > &matrix)
{
vector<int> result;
int i = 0,j = 0;
int m = matrix.size();
int n = matrix[0].size();
if(m == 0)
return vector<int>();
int startx = 0;
int endx = matrix.size() - 1;
int starty = 0;
int endy = matrix[0].size() - 1;
while(startx <= endx && starty <= endy)
{
for(j = starty; j <= endy; ++j)
{
result.push_back(matrix[startx][j]);
}
startx++;
for(i = startx; i <= endx; ++i)
{
result.push_back(matrix[i][endy]);
}
endy--;
if(startx <= endx)
{
for(j = endy; j >= starty; --j)
result.push_back(matrix[endx][j]);
}
endx--;
if(starty <= endy)
{
for(i = endx; i >= startx; --i)
{
result.push_back(matrix[i][starty]);
}
starty++;
}
}
return result;
}
};
class Solution {
public:
vector<int> spiralOrder(vector<vector<int> > &matrix)
{
vector<int> result;
int i = 0,j = 0;
if(matrix.size() == 0)
return vector<int>();
int startx = 0;
int endx = matrix.size() - 1;
int starty = 0;
int endy = matrix[0].size() - 1;
while(startx <= endx && starty <= endy)
{
for(j = starty; j <= endy; ++j)
{
result.push_back(matrix[startx][j]);
}
startx++;
for(i = startx; i <= endx; ++i)
{
result.push_back(matrix[i][endy]);
}
endy--;
if(startx <= endx)
{
for(j = endy; j >= starty; --j)
result.push_back(matrix[endx][j]);
}
endx--;
if(starty <= endy)
{
for(i = endx; i >= startx; --i)
{
result.push_back(matrix[i][starty]);
}
starty++;
}
}
return result;
}
};