首页 > 代码库 > Leetcode Spiral Matrix
Leetcode Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8, 9 ]]
You should return [1,2,3,6,9,8,7,4,5]
.
螺旋数组, 从左到右,从上到下,四个方向构建循环
循环的时候注意边界的处理
class Solution {public: vector<int> spiralOrder(vector<vector<int> > &matrix) { vector<int> res; if(matrix.empty()) return res; int dx[] = {0,1,0,-1}; int dy[] = {1,0,-1,0}; int startx = 0,endx = matrix.size(), starty = 0,endy = matrix[0].size(); int cnt = endx*endy, direction = 0, x =0 , y = 0; while(cnt > 0){ res.push_back(matrix[x][y]); matrix[x][y] = -1; cnt--; int newx = x+dx[direction], newy=y+dy[direction]; if(newx >=endx ||newx<startx || newy>=endy|| newy < starty) { direction++; if(direction%4 == 1) startx++; else if(direction%4 == 2) endy--; else if(direction%4 == 3) endx--; else starty ++; } direction%=4; x+=dx[direction];y+=dy[direction]; } return res; }};
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。