Lintcode 374 螺旋矩阵 - 题解
这道题算是一道老题了,剑指offer上就有,虽然上面的解法我感觉也就那样。之前一次面试也碰到过,我用了个递归也算是写出来了,这次改用循环又写了一遍:
描述
给定一个包含 m x n 个要素的矩阵,(m 行, n 列),按照螺旋顺序,返回该矩阵中的所有要素。
样例
给定如下矩阵:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
应返回 [1,2,3,6,9,8,7,4,5]
。
思路:其实就是定义4个方向,确定每个方向能走的步数,然后做个循环就行。
C++ AC代码:
1 class Solution { 2 public: 3 /** 4 * @param matrix: a matrix of m x n elements 5 * @return: an integer list 6 */ 7 vector<int> spiralOrder(vector<vector<int>> &matrix) { 8 // write your code here 9 vector<int> res; 10 int sizey = matrix.size(); 11 if(sizey == 0) return res; 12 int sizex = matrix[0].size(); 13 int xlen = sizex; 14 int ylen = sizey; 15 int direct = 0; 16 int index_x = 0; 17 int index_y = -1;//这个入口坐标还是挺重要的,每次都需要确定一条边遍历的起始位置! 18 while(xlen && ylen){//循环出口 19 if(direct == 0){ 20 for(int i = 1;i <= xlen; ++i){ 21 res.push_back(matrix[index_x][index_y+i]); 22 } 23 index_y += xlen; 24 ylen--; 25 }else if(direct == 1){ 26 for(int i = 1;i <= ylen;++i){ 27 res.push_back(matrix[index_x+i][index_y]); 28 } 29 index_x += ylen; 30 xlen--; 31 }else if(direct == 2){ 32 for(int i = 1;i <= xlen; ++i){ 33 res.push_back(matrix[index_x][index_y-i]); 34 } 35 index_y -= xlen; 36 ylen--; 37 }else{ 38 for(int i = 1;i <= ylen;++i){ 39 res.push_back(matrix[index_x-i][index_y]); 40 } 41 index_x -= ylen; 42 xlen--; 43 } 44 direct = (direct+1)%4;//每次改变方向,0向右,1下,2左,3上。 45 } 46 return res; 47 } 48 49 };
Know More ,Do More.