蜀icp备 网站建设中企动力成都,济南官方网站,python网站建设代码,小说网站建设源码LCR 146. 螺旋遍历二维数组 - 力扣#xff08;LeetCode#xff09;
总结#xff1a;本质是模拟一个螺旋的过程#xff0c;其中关键是如何限制边界条件或者说是循环结束条件。题目要求是按从左到右、从上到下、从右到左、从下到上的顺序#xff0c;所以可以设置循环来完成…LCR 146. 螺旋遍历二维数组 - 力扣LeetCode
总结本质是模拟一个螺旋的过程其中关键是如何限制边界条件或者说是循环结束条件。题目要求是按从左到右、从上到下、从右到左、从下到上的顺序所以可以设置循环来完成然后对其中的边界进行界定。
代码
class Solution {
public:vectorint spiralArray(vectorvectorint array) {vectorint 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:vectorvectorint 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;vectorvectorint res(n, vectorint(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;}
};