欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 教育 > 高考 > 力扣--54.螺旋矩阵

力扣--54.螺旋矩阵

2025/5/8 7:57:28 来源:https://blog.csdn.net/weixin_52297290/article/details/145002889  浏览:    关键词:力扣--54.螺旋矩阵

题目

给你一个 m 行 n 列的矩阵 matrix ,请按照 顺时针螺旋顺序 ,返回矩阵中的所有元素。
在这里插入图片描述提示:

m == matrix.length
n == matrix[i].length
1 <= m, n <= 10
-100 <= matrix[i][j] <= 100

代码

class Solution {
public List spiralOrder(int[][] matrix) {
List ans = new ArrayList<>();
int m = matrix.length, n = matrix[0].length;
int left = 0, right = n - 1, top = 0, bottom = m - 1;
while (left <= right && top <= bottom) {
// 从左到右
for (int i = left; i <= right; i++) {
ans.add(matrix[top][i]);
}
top++;
// 从上到下
for (int i = top; i <= bottom; i++) {
ans.add(matrix[i][right]);
}
right–;
// 从右到左
if (top <= bottom) {
for (int i = right; i >= left; i–) {
ans.add(matrix[bottom][i]);
}
}
bottom–;
// 从下到上
if (left <= right) {
for (int i = bottom; i >= top; i–) {
ans.add(matrix[i][left]);
}
}
left++;
}
return ans;
}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词