首页 > 代码库 > 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; int n= matrix.size(); if(n==0) return res; if(n==1) return matrix[0]; int m = matrix[0].size(); bool left_up = true; bool left_down = false; bool right_up = false; bool right_down = false; int min_i = 0; int max_i = n-1; int min_j = 0; int max_j = m-1; while(min_i<=max_i && min_j<=max_j) { if(left_up == true) { for(int j = min_j; j<=max_j; j++) res.push_back(matrix[min_i][j]); left_up = false; right_up = true; min_i = min_i+1; } else if(right_up == true) { for(int i=min_i; i<=max_i; i++) res.push_back(matrix[i][max_j]); max_j = max_j-1; right_up = false; right_down = true; } else if(right_down == true) { for(int j=max_j; j>=min_j; j--) res.push_back(matrix[max_i][j]); max_i = max_i-1; left_down = true; right_down = false; } else { for(int i=max_i; i>=min_i; i--) res.push_back(matrix[i][min_j]); min_j = min_j+1; left_up = true; left_down = false; } } return res; } };
LeetCode--Spiral Matrix
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。