力扣:54.螺旋矩阵
题目:
给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
class Solution {
public:
vector<int> spiralOrder(vector<vector<int>>& matrix) {
if (matrix.size() == 0 || matrix[0].size() == 0) {
return {};
}
int nums = 1;
int m = matrix.size();
int n = matrix[0].size();
int right = n-1, bottom = m-1, left = 0, top = 0;
vector<int> v;
while(left <= right && top <= bottom){
for(int column = left; column <= right; column++){
v.push_back(matrix[top][column]);
}
for(int row = top+1; row <= bottom; row++){
v.push_back(matrix[row][right]);
}
if(left < right && top < bottom){
for (int column = right-1; column > left; column--) {
v.push_back(matrix[bottom][column] );
}
for (int row = bottom; row > top; row--) {
v.push_back(matrix[row][left] );
}
}
top++;
right--;
left++;
bottom--;
}
return v;
}
};
循环概况:一整行,一整竖,行不到头,竖不到头。
最后一圈的几种情况:
①最后能走完一整圈 :正常情况按原先代码也能进行 (走最后一圈跳出循环)
两长行:right > left
两长列: bottom >top
正好四个:right = left && bottom = top
②最后不能走一整圈 :只有一行或者一列
right = left 、 bottom = top 两者存在一种
③一个元素
right = left && bottom = top
—————————————————————————
②的问题就是
第一三个for循环操作一行时,第一for添加所有元素,第三个for从倒数第二个元素开始逆向添加进容器中,造成重复添加。
第二四个for循环操作一列时,第二个for添加所有元素,第四个for从倒数第二个元素开始逆向添加进容器中,造成重复添加。
解决:最后一圈时,当一二for操作后,三四for不操作。
②的最后一圈:right = left 、 bottom = top 两者存在一种
通过下面一段代码解决②的问题(添加 if 条件)
if (left < right && top < bottom) {
for (int column = right - 1; column > left; column--) {
order.push_back(matrix[bottom][column]);
}
for (int row = bottom; row > top; row--) {
order.push_back(matrix[row][left]);
}
}
四个for循环依次操作的是:上线、右线、下线、左线
当只有一行或者一列时不用 这个 if 条件将下线 for 和左线 for扩起来则会将此一行或者一列的元素重复添加。
通过以下解决③的问题(重复添加)
同时处理上线、右线时依次包含left = right 、bottom = top的情况,处理下线、左线时依次不包含left = right ,bottom = top的情况,就解决了重复添加问题。