(LC) 54. Spiral Matrix

54. Spiral Matrix

Given a matrix with m rows and n columns, please follow the clockwise spiral order to return all the elements in the matrix.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [1,2,3,6,9,8,7,4,5]
Example 2:

Input: matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
Output: [1,2,3,4,8,12, 11,10,9,5,6,7]

prompt:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100
Passes 125,844 Submits 278,144

 public List<Integer> spiralOrder(int[][] matrix) {
    
    
         List<Integer> order = new ArrayList<Integer>();
		 int rows = matrix.length; // 列数
		 int colums = matrix[0].length; // 行数
		 
		 int left = 0;
		 int right = colums-1;
		 int top = 0;
		 int bottom = rows-1;
		 
		 if (matrix==null || rows==0 || colums==0) {
    
     // 刚开始就没有元素,可以直接返回空的表
			 return order;
		 }
		 
		 while (left<=right && top<=bottom) {
    
    
			 for (int colum=left; colum<=right; colum++) {
    
     // 横上
				 order.add(matrix[left][colum]);
			 }
			for (int row = top + 1; row <= bottom; row++) {
    
    
	                order.add(matrix[row][right]);
	            }
			 if (left<right && top<bottom) {
    
    
				 for (int colum=right-1; colum>left; colum--) {
    
     // 下横
					 order.add(matrix[bottom][colum]);
				 }
				 for (int row=bottom; row>top; row--) {
    
     // 有上
					 order.add(matrix[row][left]);
				 }
			 }
			 left++;
			 right--;
			 top++;
			 bottom--;
		 }
		 return order;
    }
```

Guess you like

Origin blog.csdn.net/weixin_45567738/article/details/114845349