題目描述
給你一個 m 行 n 列的矩陣 matrix ,請按照順時針螺旋順序 ,傳回矩陣中的所有元素。
示例
示例 1:![]()
leetCode-54: 螺旋矩陣 輸入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
輸出:[1,2,3,6,9,8,7,4,5]
示例 2:![]()
leetCode-54: 螺旋矩陣 輸入: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]
解題思路
步驟
(1)初始化四個方向上的邊界值,左邊界 left = 0,右邊界 right = n - 1,上邊界 top = 0,下邊界 bottom = m - 1;
(2)按照順時針螺旋的順序,依次進行從左到右,從上到下,從右到左,從下到上的周遊;
注意點:
(1)從左到右周遊的條件是上邊界 <= 下邊界,周遊完成之後記得将上邊界 top 自增 1;
(2)從上到下周遊的條件是左邊界 <= 右邊界,周遊完成之後記得将右邊界 right 自減 1;
(3)從右到左周遊的條件是上邊界 <= 下邊界,周遊完成之後記得将下邊界 bottom 自減 1;
(4)從下到上周遊的條件是左邊界 <= 右邊界,周遊完成之後記得将左邊界 left 自增 1;
代碼展示
public class SpiralOrder {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> resultList = new ArrayList<>();
int line = matrix.length;
int column = matrix[0].length;
// 上邊界
int top = 0;
// 下邊界
int bottom = line - 1;
// 左邊界
int left = 0;
// 右邊界
int right = column - 1;
while (resultList.size() < line * column) {
// 如果上邊界 <= 下邊界, 從左到右周遊
if (top <= bottom) {
fromLeftToRight(matrix, left, right, top, resultList);
top++;
}
// 如果左邊界 <= 右邊界, 從上到下周遊
if (left <= right) {
fromTopToBottom(matrix, top, bottom, right, resultList);
right--;
}
// 如果上邊界 <= 下邊界, 從右到左周遊Left
if (top <= bottom) {
fromRightToLeft(matrix, left, right, bottom, resultList);
bottom--;
}
// 如果左邊界 <= 右邊界, 從下到上周遊
if (left <= right) {
fromBottomToTop(matrix, top, bottom, left, resultList);
left++;
}
}
return resultList;
}
private static void fromBottomToTop(int[][] matrix, int top, int bottom, int left, List<Integer> resultList) {
for (int i = bottom; i >= top; i--) {
resultList.add(matrix[i][left]);
}
}
private static void fromRightToLeft(int[][] matrix, int left, int right, int bottom, List<Integer> resultList) {
for (int i = right; i >= left; i--) {
resultList.add(matrix[bottom][i]);
}
}
private static void fromTopToBottom(int[][] matrix, int top, int bottom, int right, List<Integer> resultList) {
for (int i = top; i <= bottom; i++) {
resultList.add(matrix[i][right]);
}
}
private static void fromLeftToRight(int[][] matrix, int left, int right, int top, List<Integer> resultList) {
for (int i = left; i <= right; i++) {
resultList.add(matrix[top][i]);
}
}
public static void main(String[] args) {
int[][] matrix = {{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25}};
for (int i = 0; i < matrix.length; i++) {
for (int j = 0; j < matrix[i].length; j++) {
System.out.printf("%4d", matrix[i][j]);
}
System.out.println();
}
System.out.println();
List<Integer> resultList = new ArrayList<>();
resultList = spiralOrder(matrix);
for (int i = 0; i < resultList.size(); i++) {
System.out.printf("%4d", resultList.get(i));
}
System.out.println();
}
}