C++:
class Solution { public: vector<int> spiralOrder(vector<vector<int> > &matrix) { int n=matrix.size(); if(n==0)return {}; int m=matrix[0].size(); vector<int>ans; int up=0,down=n,left=0,right=m; while(left<right&&up<down){ for(int i=left;i<right;++i)ans.push_back(matrix[up][i]); ++up; for(int i=up;i<down;++i)ans.push_back(matrix[i][right-1]); --right; for(int i=right-1;i>=left;--i)ans.push_back(matrix[down-1][i]); --down; for(int i=down-1;i>=up;--i)ans.push_back(matrix[i][left]); ++left; } while(ans.size()>m*n){ ans.pop_back(); } return ans; } };
JAVA:
import java.util.*; public class Solution { public ArrayList<Integer> spiralOrder(int[][] matrix) { int n=matrix.length; ArrayList<Integer> ans=new ArrayList<>(); if(n==0)return ans; int m=matrix[0].length; int up=0,down=n,left=0,right=m; while(left<right&&up<down){ for(int i=left;i<right;++i){ ans.add(matrix[up][i]); } ++up; for(int i=up;i<down;++i){ ans.add(matrix[i][right-1]); } --right; for(int i=right-1;i>=left;--i){ ans.add(matrix[down-1][i]); } --down; for(int i=down-1;i>=up;--i){ ans.add(matrix[i][left]); } ++left; } while(ans.size()>m*n){ ans.remove(ans.size()-1); } return ans; } }
PYTHON3:
# # # @param matrix int整型二维数组 # @return int整型一维数组 # class Solution: def spiralOrder(self , matrix ): # write code here n=len(matrix) ans=[] if n==0: return ans m=len(matrix[0]) up=0 down=n left=0 right=m while left<right and up<down: for i in range(left,right): ans.append(matrix[up][i]) up+=1 for i in range(up,down): ans.append(matrix[i][right-1]) right-=1 for i in range(right-1,left-1,-1): ans.append(matrix[down-1][i]) down-=1 for i in range(down-1,up-1,-1): ans.append(matrix[i][left]) left+=1 while len(ans)>m*n: ans.pop() return ans