Leetcode 题目解析之 Spiral Matrix
【摘要】 Leetcode 题目解析之 Spiral Matrix
Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
For example,
Given the following matrix:
[
1, 2, 3 ,
4, 5, 6 ,
7, 8, 9
]
You should return 1,2,3,6,9,8,7,4,5.
public List<Integer> spiralOrder(int[][] matrix) {
List<Integer> rt = new ArrayList<Integer>();
if (matrix == null || matrix.length == 0) {
return rt;
}
int startx = 0, endx = matrix.length - 1;
int starty = 0, endy = matrix[0].length - 1;
while (startx <= endx && starty <= endy) {
// 上边的行,从左向右
for (int y = starty; y <= endy; y++) {
rt.add(matrix[startx][y]);
}
// 右边的列,从上到下
for (int x = startx + 1; x <= endx; x++) {
rt.add(matrix[x][endy]);
}
// 如果行或列遍历完,则退出循环
if (startx == endx || starty == endy) {
break;
}
// 下边的行,从右向左
for (int y = endy - 1; y >= starty; y--) {
rt.add(matrix[endx][y]);
}
// 左边的列,从下到上
for (int x = endx - 1; x >= startx + 1; x--) {
rt.add(matrix[x][starty]);
}
startx++;
starty++;
endx--;
endy--;
}
return rt;
}
【版权声明】本文为华为云社区用户原创内容,转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息, 否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)