題意描述:
給定一個包含 m x n 個元素的矩陣(m 行, n 列),請按照順時針螺旋順序,返回矩陣中的所有元素。
示例:
示例一:
輸入:
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ]
]
輸出: [1,2,3,6,9,8,7,4,5]
示例二:
輸入:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10,11,12]
]
輸出: [1,2,3,4,8,12,11,10,9,5,6,7]
解題思路:
Alice: 這題面熟啊,我們是不是在哪見過 ?
Bob:PAT 那套題目做過啊。
Alice: 所以你還記得怎麼寫的嗎 ?
Bob: 應該還記得。就是螺旋訪問唄,假設有m行n列,先橫着往右讀取 m 個元素,在豎着往下 n-1 個元素,再橫着往左讀 m-1 個元素,再豎着往上讀 n-2 的元素,然後重複這個步驟,一直到讀完所有的元素。
Alice: 是這樣嗎 ?
Bob:就是就是。然後注意一下不要越界訪問還有邊界值輸入的處理就好了。
Alice: 😎😎
代碼:
Python 方法一:
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
if len(matrix) == 0 or len(matrix[0]) == 0:
return []
directions = [[0, 1], [1, 0], [0, -1], [-1, 0]]
i = 0
j = -1
m = len(matrix)
n = len(matrix[0])
cnt = 0
tot = m * n
ans = []
index = -1
while cnt < tot:
#print('n ', n)
index = (index + 1) % 4
for x in range(n):
i += directions[index][0]
j += directions[index][1]
ans.append(matrix[i][j])
cnt += 1
m -= 1
index = (index + 1) % 4
for x in range(m):
i += directions[index][0]
j += directions[index][1]
ans.append(matrix[i][j])
cnt += 1
n -= 1
return ans
Java 方法一:
class Solution {
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> ans = new ArrayList();
if(matrix.length == 0 || matrix[0].length == 0){
return ans;
}
int rows = matrix.length;
int cols = matrix[0].length;
int i = 0;
int j = -1;
int cnt = 0;
int tot = cols * rows;
int[][] directions = {{0,1}, {1,0}, {0,-1}, {-1,0}};
int index = -1;
while(cnt < tot){
index = (index + 1) % 4;
for(int x=0; x<cols; ++x){
i += directions[index][0];
j += directions[index][1];
ans.add(matrix[i][j]);
cnt++;
}
rows--;
index = (index + 1) % 4;
for(int x=0; x<rows; ++x){
i += directions[index][0];
j += directions[index][1];
ans.add(matrix[i][j]);
cnt++;
}
cols--;
}
return ans;
}
}
易錯點:
- 一些測試點:
[[1,2,3],[4,5,6],[7,8,9]]
[[1,2,3,4],[5,6,7,8]]
[[1],[2]]
[[1]]
[[2,3],[4,5]]
[[]]
[]
- 答案:
[1,2,3,6,9,8,7,4,5]
[1,2,3,4,8,7,6,5]
[1,2]
[1]
[2,3,5,4]
[]
[]
總結: