No.209 - LeetCode[54] Spiral Matrix - 矩阵蛇形输出 - Coding基础

tech2024-04-16  13

直接用一个等大矩阵来染色比较好写。

不用额外空间,写起来就比较麻烦。

核心思想,每一层加loc超容判断,a,b两个方向的游标。

/* * @lc app=leetcode id=54 lang=cpp * * [54] Spiral Matrix */ // @lc code=start class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if(matrix.size() <= 0){ return *(new vector<int>); } int M = matrix.size(); int N = matrix[0].size(); int T = N*M; vector<int> ans(T,0); int loc = 0; int a = 0 , b = 0; // 层 int L = (min(N,M)+1)/2; for(int i=0;i<L;i++){ // 上一层 while(loc < T && b < N-1-i){ ans[loc++] = matrix[a][b++]; } // 右一层 while(loc < T && a < M-1-i){ ans[loc++] = matrix[a++][b]; } // 下一层 while(loc < T && b > i){ ans[loc++] = matrix[a][b--]; } // 左一层 while(loc < T && a > i){ ans[loc++] = matrix[a--][b]; } a++;b++; } if( loc < T) ans[loc++] = matrix[M/2][N/2]; return ans; } }; // @lc code=end
最新回复(0)