剑指Offer29 -- 模拟

1. 题目描述

打印蛇形矩阵



2. 思路

  1. 状态机模拟
  2. 我称之为模拟优化,因为代码少,简洁,优化


3. 代码(模拟优化)

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        int n, m;
        if(!(n = matrix.size()) || !(m = matrix[0].size()))   return {};
        vector<int> res;
        int left = 0, right = m - 1;
        int top = 0, down = n - 1;
        while(left <= right && top <= down) {
            cout << left << ' ' << right << endl << top << ' ' << down << endl;
            for(int i = left; i <= right; i ++ )     res.emplace_back(matrix[top][i]);
            for(int i = top + 1; i <= down; i ++ )   res.emplace_back(matrix[i][right]);
            if(top != down) // 特判,不然同一行,从左到右走和从右到左走会重复
            for(int i = right - 1; i >= left; i -- ) res.emplace_back(matrix[down][i]);
            if(left != right)   // 特判,不然同一行从上到下走和从下到上走重复了
            for(int i = down - 1; i >= top + 1; i -- )   res.emplace_back(matrix[i][left]);
            left ++ , right -- , down -- , top ++ ;
        }
        return res;
    }
};
/*
[[1]]
[[1,2],[3,4]]
[[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3,4],[5,6,7,8],[9,10,11,12]]
[[1,2,3,4,11],[5,6,7,8,22],[9,10,11,12,33],[44,55,66,77,88]]

1  2  3  4
5  6  7  8
9 10 11 12
*/
posted @ 2023-03-06 10:57  光風霽月  阅读(8)  评论(0编辑  收藏  举报