螺旋矩阵 Spiral Matrix

目录

  • 问题描述
  • 边界索引
    • C++

问题描述

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.

Example 1:
Input:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
Output: [1,2,3,6,9,8,7,4,5]

边界索引

依次遍历外围的数值,每次遍历一行或者一列之后,需要调整边界大小(up,down,right,left四个边),并且判断是否已经遍历完成(当up>down,left>right说明要超出边界了,已经遍历完成所有)。

C++

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if(matrix.empty()||matrix[0].empty()) return {};
        vector<int> result;
        int height = matrix.size();
        int width = matrix[0].size();
        int up=0, down=height-1, left=0, right=width-1;
        
        while(true)
        {
            //from left to right
            for(int i=left;i<=right;i++)
                result.push_back(matrix[up][i]);
            if(++up>down)
                break;
            
            // form up to down
            for(int i=up;i<=down;i++)
                result.push_back(matrix[i][right]);
            if(--right<left)
                break;
            
            // from right to left
            for(int i=right; i>=left;i--)
                result.push_back(matrix[down][i]);
            if(--down<up)
                break;
            
            // from down to up
            for(int i=down;i>=up;--i)
                result.push_back(matrix[i][left]);
            if(++left>right)
                break;
        }
        return result;
    }
};

你可能感兴趣的:(数据结构与算法,leetcode)