先來看題:
給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。
示例 1:
輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例 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]
這是leetcode上一個難度偏高的題,據說也是騰訊的一個筆試題,因爲在網上找不到合適的解答,所以我自己實現了一下, 做個總結,希望對大家有幫助:
思路:
首先看到這個題目,最先想到的就是用遞歸來實現,螺旋矩陣輸出其實就是從外層到內層一圈一圈地輸出,
每一圈就作爲一個遞歸過程。
每一個遞歸過程分爲四個步驟:
1、從左往右
2、從上到下
3、從右到左
4、從下到上
所以,我們的算法結構就是設計一個遞歸,遞歸的每一層包含以上四個輸出。
java代碼實現如下:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
ArrayList<Integer> resultList = new ArrayList<Integer>() ;
if(matrix.length == 0){
return resultList;
}
//nums.length 行數,nums[0].length:列數
resultList = getEachSort(resultList, matrix, 0, matrix[0].length-1, 0, matrix.length-1);
return resultList;
}
public static ArrayList getEachSort(ArrayList<Integer> resultList,
int[][] nums, int beginI, int endI, int beginJ, int endJ){
for(int j=beginI; j<=endI; j++){
resultList.add(nums[beginJ][j]);
}
for(int i=beginJ+1; i<=endJ; i++){
resultList.add(nums[i][endI]);
}
if(endJ>beginJ){
for(int k=endI-1; k>=beginI; k--){
resultList.add(nums[endJ][k]);
}
}
if(beginI<endI){
for(int p=endJ-1; p>=beginJ+1; p--){
resultList.add(nums[p][beginI]);
}
}
beginI++;
endI--;
beginJ++;
endJ--;
if(beginI<=endI && beginJ<=endJ){
getEachSort(resultList, nums, beginI, endI, beginJ, endJ);
}
return resultList;
}
}