LeetCode筆記——54螺旋矩陣
題目:
給定一個包含 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]
思路:大神們還是很牛的,直接看了大神的程式碼。這個題主要是搞清楚座標的轉換。首先先確定螺旋的圈數,然後按照上面,右面,下面,左面的順序依次處理資料。要特別注意範圍。
程式碼:
public class Solution {
public List<Integer> spiralOrder(int[][] matrix) { List<Integer> result = new ArrayList<>(50); //存放最後的結果
if (matrix == null || matrix.length == 0 || matrix[0].length == 0) { return result; //矩陣為空 }
// 只有一行的情況 要特別注意,對矩陣求length結果返回的是行數 if (matrix.length
return result; }
// 只有一列的情況 返回列數 if (matrix[0].length == 1) { for (int i = 0; i < matrix.length; i++) { result.add(matrix[i][0]); }
return result; }
// 計算有多少圈 int row = matrix.length; int col = matrix[0].length; int cycle = row < col ? row : col; //取行列中最小的一個 cycle = (cycle + 1) / 2;
int round = 0; // 記錄當前是第幾圈 int left = 0; //第一列 int right = matrix[0].length - 1; //最後一列 int top = 0; //第一行 int down = matrix.length - 1; //最後一行 int total = col*row; int count = 0; while (round < cycle) {
// 上面一行 for (int i = left; i <= right && count < total; i++) { count++; result.add(matrix[round][i]); } top++; //處理下一行
// 右邊一列 for (int i = top; i <= down && count < total; i++) { count++; result.add(matrix[i][col - round - 1]); } right--;
// 底下一行 for (int i = right; i >= left && count < total; i--) { count++; result.add(matrix[row - round - 1][i]);
} down--;
// 左邊一列 for (int i = down; i >= top && count < total; i--) { count++; result.add(matrix[i][round]); } left++;
round++; }
return result; } }