題目信息
給你一個(gè) m 行 n 列的矩陣 matrix 阵难,請(qǐng)按照 順時(shí)針螺旋順序 ,返回矩陣中的所有元素芒填。
示例 1:
matrix3_4.jpg
輸入: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]
解題思路
- 暴力破解:
- 無(wú)效操作分析:
- 優(yōu)化方法:
- 考慮邊界
- 編碼實(shí)現(xiàn)
代碼
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;
}
// 獲取循環(huán)數(shù)量
int rows = matrix.length, columns = matrix[0].length;
int left = 0, right = columns - 1, top = 0, bottom = rows - 1;
while (left <= right && top <= bottom){
// 上
for (int column = left; column <= right; column++) {
result.add(matrix[top][column]);
}
// 右
for (int row = top + 1; row <= bottom; row++) {
result.add(matrix[row][right]);
}
if (left < right && top < bottom) {
// 下
for (int column = right - 1; column > left; column--) {
result.add(matrix[bottom][column]);
}
// 左
for (int row = bottom; row > top; row--) {
result.add(matrix[row][left]);
}
}
left++;
right--;
top++;
bottom--;
}
return result;
}
}
題目來(lái)源:力扣(LeetCode)
題目鏈接:https://leetcode-cn.com/problems/spiral-matrix
商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán)呜叫,非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。