Spiral Matrix

来源:互联网 发布:百合 知乎 编辑:程序博客网 时间:2024/06/16 18:45

题目描述:

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].

解题思路:

使用一个数组steps记录四个方向上(向右,向下,向左,向上)每次可以移动的步长,steps数组初始化为[n, m - 1, n - 1, m - 2],
每经过一圈每个方向上的移动步长就减2,如果遇到某方向上的移动步长小于等于0,则说明所有的元素都已经访问。
另外需要注意第一圈向右移动的步长和其它圈的向右移动的步长的处理有些不一样,
这是因为第一圈向右移动的时候所有第一行的元素都还没有被访问。


AC代码如下:

class Solution {public:vector<int> spiralOrder(vector<vector<int>>& matrix) {vector<int> ans;if (matrix.size() == 0 || matrix[0].size() == 0) return ans;int m = matrix.size();int n = matrix[0].size();vector<int> steps = { n, m - 1, n - 1, m - 2 };int row = 0, col = 0;int times = 0;while (1){//向右if (steps[0] > 0){if (times == 0){for (int i = 0; i < steps[0]; ++i){ans.push_back(matrix[row][col+i]);}col += steps[0] - 1;}else{for (int i = 1; i <= steps[0]; ++i){ans.push_back(matrix[row][col+i]);}col += steps[0];}++times;steps[0] -= 2;}else{break;}//向下if (steps[1]>0){for (int i = 1; i <= steps[1]; ++i){ans.push_back(matrix[row+i][col]);}row += steps[1];steps[1] -= 2;}else{break;}//向左if (steps[2] > 0){for (int i = 1; i <= steps[2]; ++i){ans.push_back(matrix[row][col-i]);}col -= steps[2];steps[2] -= 2;}else{break;}//向上if (steps[3] > 0){for (int i = 1; i <= steps[3]; ++i){ans.push_back(matrix[row-i][col]);}row -= steps[3];steps[3] -= 2;}else{break;}}return ans;}};


0 0
原创粉丝点击