leetcode第十周解题总结

来源:互联网 发布:联通ssr免流端口2017 编辑:程序博客网 时间:2024/05/29 17:32

54. 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> result;        int m = matrix.size();        if (m == 0) return result;        int n = matrix[0].size();        int row = 0;        int col = -1;        while (true) {            for(int i = 0; i < n; i ++) {                col++;                result.push_back(matrix[row][col]);            }            m--;            if(m == 0) break;            for(int i = 0; i < m; i ++) {                row++;                result.push_back(matrix[row][col]);            }            n--;            if(n == 0) break;            for(int i = 0; i < n; i ++) {                col--;                result.push_back(matrix[row][col]);            }            m--;            if(m == 0) break;            for(int i = 0; i < m; i ++) {                row--;                result.push_back(matrix[row][col]);            }            n--;            if(n == 0) break;        }        return result;    }};
0 0