Spiral Matrix -- LeetCode

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

思路:规律:当我们沿水平方向走完一次(比如从左往右),则下一次水平方向(从右向左)要走的长度为这一次减一。竖直方向也是一样的规律。

拿题目中的这个矩阵为例子,第一次水平方向走了1, 2, 3,然后竖直方向6, 9,然后又是水平方向8, 7, 然后竖直方向4, 然后水平方向5。整个过程中,水平方向走的距离依次是3,2,1,竖直方向走的距离依次是2,1。

对于一个M行N列的矩阵,则水平方向走的距离应该是N, N-1, N-2, ...., 1,竖直方向走的距离为M-1, M-2, ..., 1。

之后就简单了,我们从左上角matrix[0][0]出发,然后只要知道自己当前要走的方向和要走的距离,就能解决这个问题了。

 1 class Solution {
 2 public:
 3     vector<int> spiralOrder(vector<vector<int>>& matrix) {
 4         vector<int> res;
 5         if (matrix.size() == 0) return res;
 6         int height(matrix.size() - 1), width(matrix[0].size()), row(0), col(-1);
 7         bool goRow(true), goForward(true);
 8         while ((goRow && width > 0) || (!goRow && height > 0)) {
 9             if (goRow) {
10                 for (int i = 0; i < width; i++)
11                     res.push_back(goForward ? matrix[row][++col] : matrix[row][--col]);
12                 width--;
13                 goRow = !goRow;
14             } else {
15                 for (int i = 0; i < height; i++)
16                     res.push_back(goForward ? matrix[++row][col] : matrix[--row][col]);
17                 height--;
18                 goRow = !goRow;
19                 goForward = !goForward;
20             }
21         }
22         return res;
23     }
24 };
原文地址:https://www.cnblogs.com/fenshen371/p/5787190.html