力扣,https://leetcode.cn/problems/shun-shi-zhen-da-yin-ju-zhen-lcof/description/
Python
class Solution:
def spiralArray(self, array: List[List[int]]) -> List[int]:
res = list()
if len(array) == 0 or len(array[0]) == 0:
return res
m, n = len(array), len(array[0])
m1, n1 = 0, 0
m2, n2 = m-1, n-1
while m1 <= m2 and n1 <= n2:
for i in range(n1, n2+1): # 向右
res.append(array[m1][i])
for i in range(m1+1, m2): # 向下
res.append(array[i][n2])
for i in range(n2, n1-1, -1): # 向左
if m1 == m2:
break
res.append(array[m2][i])
for i in range(m2-1, m1, -1): # 向上
if n1 == n2:
break
res.append(array[i][n1])
n1 += 1
m1 += 1
n2 -= 1
m2 -= 1
return res
Java
更新java版,代码更简练,脑瓜子要清晰!!!
注意:横向打印时,索引到两头;纵向打印时,索引只取中间!!!
class Solution {
public int[] spiralArray(int[][] array) {
if (array.length == 0 || array[0].length == 0) {
return new int[0];
}
int xLeftUp = 0, yLeftUp = 0, xRightDown = array.length - 1, yRightDown = array[0].length - 1;
int[] res = new int[array.length * array[0].length];
int i = 0;
while (xLeftUp <= xRightDown && yLeftUp <= yRightDown) {
for (int k = yLeftUp; k <= yRightDown; ++k) { // 向右
res[i++] = array[xLeftUp][k];
}
for (int k = xLeftUp + 1; k < xRightDown; ++k) { // 向下
res[i++] = array[k][yRightDown];
}
for (int k = yRightDown; k >= yLeftUp && xLeftUp < xRightDown; --k) { // 向左
res[i++] = array[xRightDown][k];
}
for (int k = xRightDown - 1; k > xLeftUp && yLeftUp < yRightDown; --k) { // 向上
res[i++] = array[k][yLeftUp];
}
++xLeftUp;
++yLeftUp;
--xRightDown;
--yRightDown;
}
return res;
}
}
Solution1:
可参考leetCode 54题的解法
书上的思路特别好,学习之~
class Solution {
public:
vector<int> printMatrix(vector<vector<int> > matrix) {
vector<int> res;
int rows = matrix.size(), cols = matrix[0].size();
if(rows == 0 || cols == 0)
return res;
int i = 0, j = 0;//循环变量
while(i <= rows-1-i && j <= cols-1-j){
PrintCycle(matrix, res, i, j, rows-1, cols-1);
i++;
j++;
}
return res;
}
void PrintCycle(vector<vector<int> > &matrix, vector<int> &result, int m, int n, int row, int col){
int i = 0, j = 0;
for(j=n;j<=col-n;j++)
result.push_back(matrix[m][j]);
for(i=m+1;i<=row-m;i++)
result.push_back(matrix[i][col-n]);
for(j=col-n-1;j>=n && m+1<=row-m;j--)//只有row-m行不与m行重合时才往回push_back
result.push_back(matrix[row-m][j]);
for(i=row-m-1;i>m && col-n-1>=n;i--)//只有n行不与col-n行重合时才往上push_back
result.push_back(matrix[i][n]);
}
};
本文提供了一种使用Java实现的顺时针打印矩阵的方法。通过定义边界和循环遍历的方式,实现了对矩阵的有效遍历与打印。代码简洁高效,易于理解。
2772





