链接:
https://leetcode.com/problems/spiral-matrix/
大意:
给定一个二维数组,对数组进行螺旋遍历(具体什么是螺旋遍历,请看例子)。例子:
思路:
与之前的二维数组顺时针旋转90度类似:https://blog.csdn.net/smart_ferry/article/details/88820560
也是从最外围往内遍历 ,具体思路看代码及注释。
代码:
class Solution {
public List<Integer> spiralOrder(int[][] m) {
LinkedList<Integer> res = new LinkedList<>();
if (m.length == 0)
return res;
helper(0, m.length - 1, 0, m[0].length - 1, m, res);
return res;
}
public void helper(int rowStart, int rowEnd, int colStart, int colEnd, int[][] m, LinkedList<Integer> res) {
// rowStart > rowEnd 或者 colStart > colEnd 时 直接跳出递归
if (rowStart > rowEnd || colStart > colEnd)
return ;
// 只剩下同一行的数据
if (rowStart == rowEnd) {
while (colStart <= colEnd) {
res.addLast(m[rowStart][colStart++]);
}
return ;
}
// 只剩下同一列的数据
if (colStart == colEnd) {
while (rowStart <= rowEnd) {
res.addLast(m[rowStart++][colStart]);
}
return ;
}
// 螺旋遍历
// 首先在起始行rs 遍历元素为[cs,ce) 再在末尾列ce 遍历元素为[rs,re) 再在末尾行re 遍历元素为[ce,cs) 再在起始列 遍历元素为[re,rs)
int rs = rowStart, re = rowEnd, cs = colStart, ce = colEnd;
while (cs < ce) {
res.addLast(m[rs][cs++]);
}
cs = colStart;
while (rs < re) {
res.addLast(m[rs++][ce]);
}
rs = rowStart;
while (ce > cs) {
res.addLast(m[re][ce--]);
}
ce = colEnd;
while (re > rs) {
res.addLast(m[re--][cs]);
}
re = rowEnd;
helper(rs + 1, re - 1, cs + 1, ce - 1, m, res);
}
}
结果:
结论:
自我感觉,思路很清晰,代码写起来也只不过是敲键盘的事。
唯一可能觉得需要改进的应该就是代码的冗余度了吧