1. 題目
給你一個 m 行 n 列的矩陣 matrix ,請按照 順時針螺旋順序 ,返回矩陣中的所有元素。
示例 1:
輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]
示例 2:
輸入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
輸出:[1,2,3,4,8,12,11,10,9,5,6,7]
2. 題解
class Solution {public List<Integer> spiralOrder(int[][] matrix) {List<Integer> result = new ArrayList<>();if(matrix == null || matrix.length == 0 || matrix[0].length == 0){return result;}int top = 0, bottom = matrix.length - 1; //上下邊界int left = 0, right = matrix[0].length - 1; //左右邊界while(top <= bottom && left <= right){//從左到右遍歷當前的上邊界for(int i = left; i <= right; i++){result.add(matrix[top][i]);}top++; //上邊界縮小//從上到下遍歷當前右邊界for(int i = top; i <= bottom; i++){result.add(matrix[i][right]);}right--; //右邊界縮小//從右到左遍歷當前下邊界(需要檢查上下邊界是否相交)if(top <= bottom){for(int i = right; i >= left; i--){result.add(matrix[bottom][i]);}bottom--; //下邊界縮小}//從下往上遍歷當前左邊界(需要檢查左右邊界是否相交)if(left <= right){for(int i = bottom; i>=top; i--){result.add(matrix[i][left]);}left++; //左邊界縮小}}return result;}}
3. 解析
-
List result = new ArrayList<>();
初始化一個空列表來存儲結果,因為我們從左上角開始以螺旋的順序遍歷矩陣。 -
if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return result;
如果輸入的矩陣為空或者沒有元素,則返回已經初始化的空列表。 -
int top = 0, bottom = matrix.length - 1; int left = 0, right = matrix[0].length - 1;
定義四個變量來表示矩陣的邊界。頂部、底部、左側和右側分別對應行號和列號,用于跟蹤遍歷過程中的位置。 -
while(top <= bottom && left <= right) { … }
這段代碼使用循環來以螺旋的順序訪問矩陣,從外到內進行遍歷。條件是邊界沒有相交(即,我們還沒有完全遍歷完整個矩陣)。 -
for(int i = left; i <= right; i++) { result.add(matrix[top][i]); } top++;
從頂部行的左側到右側的元素進行循環遍歷,并將它們添加到結果列表中。然后,上邊界向下移動一步(因為我們已經訪問了這一行中的所有元素)。 -
for(int i = top; i <= bottom; i++) { result.add(matrix[i][right]); } right–;
從右側列的頂部到底部的元素進行循環遍歷,并將它們添加到結果列表中。然后,有邊界向左移動一步(因為我們已經訪問了這一列中的所有元素)。 -
if(top <= bottom) { for(int i = right; i >= left; i–) { result.add(matrix[bottom][i]); } bottom–; }
如果頂部和底部沒有相交,說明我們還沒有遍歷完最外層的矩陣。這段代碼從右側行的底部到底部的元素進行循環遍歷(向后移動)并將它們添加到結果列表中。然后,下邊界向上移動一步。 -
if(left <= right) { for(int i = bottom; i >= top; i–) { result.add(matrix[i][left]); } left++; }
如果左側和右側沒有相交,說明我們還沒有遍歷完最外層的矩陣。這段代碼從底部行的左側到頂部的元素進行循環遍歷(向下移動)并將它們添加到結果列表中。然后,左邊界向右移動一步。 -
return result;
在訪問完整個矩陣后,返回最終的結果列表。