54 螺旋矩阵

54 螺旋矩阵 题目给你一个 m 行 n 列的矩阵 matrix 请按照 顺时针螺旋顺序 返回矩阵中的所有元素。示例 1输入matrix [[1,2,3],[4,5,6],[7,8,9]]输出[1,2,3,6,9,8,7,4,5]示例 2输入matrix [[1,2,3,4],[5,6,7,8],[9,10,11,12]]输出[1,2,3,4,8,12,11,10,9,5,6,7]思路没有较为简单的方法就是模拟法。设定四个边界左右上下然后依次遍历上面的一行右边的一列底部的一行以及左边的一列每次遍历完后将对应的边界缩小然后对比边界是否重叠。代码classSolution{public:vectorintspiralOrder(vectorvectorintmatrix){inttop0,buttonmatrix.size(),left0,rightmatrix[0].size();vectorintres;while(topbuttonleftright){for(intileft;iright;i){res.push_back(matrix[top][i]);}top;if(topbutton)break;for(intitop;ibutton;i){res.push_back(matrix[i][right-1]);}right--;if(rightleft)break;for(intiright-1;ileft;i--){res.push_back(matrix[button-1][i]);}button--;if(buttontop)break;for(intibutton-1;itop;i--){res.push_back(matrix[i][left]);}left;}returnres;}};**注意**底部和右边的边界都比序列大1所以记得在遍历的时候减去避免越界访问。感谢 感谢华南溜达虎 力扣blind 75