(LC)54。スパイラルマトリックス

54.スパイラルマトリックス

m行n列の行列がある場合、時計回りのスパイラル順序に従って、行列内のすべての要素を返します。

例1:

入力:行列= [[1,2,3]、[4,5,6]、[7,8,9]]
出力:[1,2,3,6,9,8,7,4,5]
例2:例2:

入力:行列= [[1,2,3,4]、[5,6,7,8]、[9,10,11,12]]
出力:[1,2,3,4,8,12、 11,10,9,5,6,7]

促す:

m == matrix.length
n == matrix [i] .length
1 <= m、n <= 10-100
<= matrix [i] [j] <= 100
パス125,844送信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;
    }
```

おすすめ

転載: blog.csdn.net/weixin_45567738/article/details/114845349