(LC) 54. Matriz en espiral

54. Matriz espiral

Dada una matriz con m filas yn columnas, siga el orden en espiral en el sentido de las agujas del reloj para devolver todos los elementos de la matriz.

Ejemplo 1:

Entrada: matriz = [[1,2,3], [4,5,6], [7,8,9]]
Salida: [1,2,3,6,9,8,7,4,5]
Ejemplo 2:

Entrada: matriz = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
Salida: [1,2,3,4,8,12, 11,10,9,5,6,7]

inmediato:

m == matrix.length
n == matrix [i] .length
1 <= m, n <= 10
-100 <= matrix [i] [j] <= 100
Pases 125,844 Envíos 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;
    }
```

Supongo que te gusta

Origin blog.csdn.net/weixin_45567738/article/details/114845349
Recomendado
Clasificación