[牛客网-Leetcode] #Array is harder spiral-matrix

Spiral -matrix

Title description

Given an mxn size matrix (m rows, n columns), all elements in the matrix are returned 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].

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

Problem-solving ideas

  • Think of the spiral matrix as a concentric matrix, traversing in a clockwise order from the outside to the inside layer by layer .
  • Set four boundaries: left, right, top, bottom, the initial values ​​are 0, n-1, 0, m-1 respectively
  • The four boundary ranges of each concentric matrix (starting from the upper side) are left ~ right, top + 1 ~ bottom, right-1 ~ left, bottom + 1~top-1
  • After traversing a concentric matrix, left++, right- -, top- -, bottom++
  • Note that the difference between this question and Spiral Matrix Question II is that after traversing the upper boundary and the right boundary, when traversing the lower boundary and the left boundary, respectively, you need to add the judgment top <bottom and left <right, otherwise the upper and lower boundaries or left and right When the boundary overlaps, the reading will be repeated.
class Solution {
    
    
public:
    vector<int> spiralOrder(vector<vector<int> > &matrix) {
    
    
        vector<int> res;
        int m = matrix.size();
        if(0 == m) return res; 
        int n = matrix[0].size();
        
        //四个边界
        int left(0), right(n - 1), top(0), bottom(m - 1);
        while(left <= right && top <= bottom) {
    
    
            //上边界
            for(int i = left; i <= right; i ++) {
    
    
                res.push_back(matrix[top][i]);
            }
            //右边界
            for(int i = top + 1; i <= bottom; i ++) {
    
    
                res.push_back(matrix[i][right]);
            }
            //注意要加判断,如果top==bottm,则代表上下边界重合了,需要跳过
            if(top < bottom) {
    
    
                //下边界
                for(int i = right - 1; i >= left; i --) {
    
    
                    res.push_back(matrix[bottom][i]);
                }
            }
            //注意要加判断,如果left==right,则代表左右边界重合了,需要跳过
            if(left < right) {
    
    
                //左边界
                for(int i = bottom - 1; i >= top + 1; i --) {
    
    
                    res.push_back(matrix[i][left]);
                }
            }
            //进入下一个内层
            left ++; right --; top ++; bottom --;
        }
        return res;
    }
};

Guess you like

Origin blog.csdn.net/cys975900334/article/details/106597966