1. 程式人生 > 其它 >Leetcode 螺旋矩陣

Leetcode 螺旋矩陣

技術標籤:leetcode題集leetcode

螺旋矩陣

題目描述:

給你一個 m 行 n 列的矩陣 matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。 提示: m == matrix.length n == matrix[i].length 1 <= m, n <= 10 -100 <= matrix[i][j] <= 100

題目連結

示例

在這裡插入圖片描述

class Solution {
    private List<Integer> result;
    private int[][] matrix;
    public
List<Integer> spiralOrder(int[][] matrix) { this.matrix = matrix; this.result = new ArrayList<Integer>(); screw(0,matrix[0].length,matrix.length); // 開始遞迴位置(0,0) 此時邊界的寬度為matrix[0].length和高度為matrix.length return result; } private void screw(int begin,int width,
int height){ // 向右邊遍歷 for(int i = 0 ; i<width ; i++){ result.add(this.matrix[begin][i+begin]); } if(height == 1) return; // 向下邊遍歷 for(int i = 1 ; i<height ; i++){ result.add(this.matrix[begin+i][begin+width-1]); } if
(width == 1) return; // 向左邊遍歷 for(int i = 1 ; i<width ; i++){ result.add(this.matrix[begin+height-1][begin+width-i-1]); } if(height == 2) return; // 向上邊遍歷 for(int i = 1 ; i<height-1 ; i++){ result.add(this.matrix[begin+height-1-i][begin]); } if(width > 2 && height > 2) screw(begin+1,width-2,height-2); } }

筆者初看該題,就覺得有一些遞迴的味道在裡面了,因為它每次都是遍歷最外層,一層一層向裡面遞迴,這裡的難點就是如何正確地參照每一次當前遞迴的原點座標,使之能有效遍歷。有關一些細節請看程式碼。