LeetCode刷题记录——day8

https://leetcode.cn/problems/spiral-matrix/description/?envType=study-plan-v2&envId=2024-spring-sprint-100
注意每次改变边界都有判断一次

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
        vector<int> ans(matrix.size()*matrix[0].size());
        int high=0,down=matrix.size()-1,left=0,right=matrix[0].size()-1;
        int flag_ans=0;
        while(1){
            for(int i=left;i<=right;i++){
                ans[flag_ans]=matrix[high][i];
                flag_ans++;
            }
            high++;
            if(high>down) break;
            for(int i=high;i<=down;i++){
                ans[flag_ans]=matrix[i][right];
                flag_ans++;
            }
            right--;
            if(right<left) break;
            for(int i=right;i>=left;i--){
                ans[flag_ans]=matrix[down][i];
                flag_ans++;
            }
            down--;
            if(down<high) break;
            for(int i=down;i>=high;i--){
                ans[flag_ans]=matrix[i][left];
                flag_ans++;
            }
            left++;
            if(left>right) break;
        }
        return ans;
    }
};
posted @ 2024-03-29 23:03  想成为编程高手的阿曼  阅读(8)  评论(0编辑  收藏  举报