题目: 螺旋化输出矩阵
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].
思路: 递归
1. 以一圈为一次递归 比如上面的 1 2 3 6 9 8 7 4
2. 设置四个指针 top base left right
3. 四个for 取得四边的所有点 (方法有点二)
public class Solution {
public static List<Integer> spiralOrder(int[][] matrix) {
List<Integer> res = new ArrayList<> ();
if(matrix == null || matrix.length == 0) return res;
spirial(matrix , 0 , res);
return res;
}
static void spirial(int[][] matrix , int count , List<Integer> res) {
int rows = matrix.length;
int cols = matrix[0].length;
int top = count;
int right = cols - count - 1;
int left = count;
int base = rows - count - 1;
// 递归出口
if(top > base || right < 0 || left >= cols || left > right) return ;
if(top == base) {
for(int i = left ; i <= right ; i++) {
res.add(matrix[top][i]);
}
return ;
}
//上
for(int i = count ; i < right ; i++) {
res.add(matrix[count][i]);
}
//右
for(int i = top ; i < base ; i++) {
res.add(matrix[i][right]);
}
// 下
for(int i = right ; i > left ; i--) {
res.add(matrix[base][i]);
}
//左
for(int i = base ; i > top ; i--) {
res.add(matrix[i][left]);
if(left == right) {
break;
}
}
spirial(matrix , count + 1 , res);
}
}