LCR 146. 螺旋遍历二维数组 - 力扣(LeetCode)
总结:本质是模拟一个螺旋的过程,其中关键是如何限制边界条件或者说是循环结束条件。题目要求是按从左到右、从上到下、从右到左、从下到上的顺序,所以可以设置循环来完成,然后对其中的边界进行界定。
代码:
class Solution {
public:vector<int> spiralArray(vector<vector<int>>& array) {vector<int> res;if(array.size() == 0)return res;int l = 0;int r = array[0].size() - 1;int t = 0;int b = array.size() - 1;while(true){for (int i = l; i <= r; i++) res.push_back(array[t][i]);if (++t > b) break;for (int i = t; i <= b; i++) res.push_back(array[i][r]);if (--r < l) break;for (int i = r; i >= l; i--) res.push_back(array[b][i]);if (--b < t) break;for (int i = b; i >= t; i--) res.push_back(array[i][l]);if (++l > r) break;}return res;}
};
这里要提一下另一道题目:59. 螺旋矩阵 II - 力扣(LeetCode)
这两道题目都比较相似,都是模拟一个螺旋的过程,主要区别在于第二道题的螺旋矩阵一定是一个正方形,在解题方法上也有些许区别,相同点是都是利用循环来完成,不同点是第一种更妙。
代码:
class Solution {
public:vector<vector<int>> generateMatrix(int n) {int loop = n / 2;int mid = n / 2;int startx = 0;int starty = 0;int offset = 1;int i,j;int count = 1;vector<vector<int>> res(n, vector<int>(n, 0));while(loop){i = startx;j = starty;for(j = starty;j < n - offset;j++)res[startx][j] = count++;for(i = startx; i < n - offset;i++)res[i][j] = count++;for(;j > starty;j--)res[i][j] = count++;for(;i > startx;i--)res[i][j] = count++;startx++;starty++;offset++;loop--;}if(n % 2 != 0)res[mid][mid] = n * n;return res;}
};