我尝试解决Leetcode 问题54 - 螺旋矩阵,但在空向量输入时遇到了困难。
这个问题是关于螺旋列表的。输入是一个二维向量,输出应该是一个按螺旋方向写成的向量列表。
Input:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
Output: [1,2,3,4,8,12,11,10,9,5,6,7]
问题在于输入为空列表。
Input: []
它产生了运行时错误。
除了空输入(如[])之外,其他测试用例都通过了。
在我的Mac OSX终端中进行测试似乎没有运行时错误,但Leetcode说:
'Line 933: Char 34: runtime error: reference binding to null pointer of type 'struct value_type' (stl_vector.h) '
这是链接 https://leetcode.com/problems/spiral-matrix/
我还附上了代码...
class Solution {
public:
vector<int> answer;
int left = 0, right = 0;
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if(matrix[0].size()<1) return {};
vector<vector<int>> flag(matrix.size(),vector<int>(matrix[0].size(),0));
while(1){
flag[left][right] =1;
answer.push_back(matrix[left][right]);
if(right+1<matrix[0].size() && flag[left][right+1] == 0){
++right;
continue;
}
else if(left+1<matrix.size() && flag[left+1][right] == 0 ){
++left;
continue;
}
else if(right-1>=0 && flag[left][right-1]==0){
--right;
continue;
}
else if(left-1>=0 && flag[left-1][right]==0){
--left;
continue;
}
else break;
}
return answer;
}
};
matrix
不是空的吗?如果是空的,那么matrix[0]
将表现出未定义的行为。你很好奇为什么需要检查第二维的大小,但没有检查第一维。 - Igor Tandetnik