螺旋矩阵
题目地址:螺旋矩阵
按照题意其实是有两种思路,一个是模拟题意行动,遇到超过边界的情况就转方向,设置一个visit访问矩阵,这种方法感觉很麻烦。
第二种是比较好理解的,把矩阵层层剥开,一层一层去访问,代码写起来也比较好理解。
package test;
import java.util.LinkedList;
import java.util.List;
public class Test {
public static void main(String[] args) {
int[][] matrix = {{1,2,3},{4,5,6},{7,8,9}};
System.out.println(spiralOrder(matrix));
}
public static List<Integer> spiralOrder(int[][] matrix) {
LinkedList<Integer> result = new LinkedList<>();
if(matrix == null || matrix.length == 0) return result;
//定义四个边角
int top = 0;
int left = 0;
int bottom = matrix.length - 1;
int right = matrix[0].length - 1;
int numElm = matrix.length * matrix[0].length;//元素个数
while(numElm >= 1){
//最上层
for(int i = left; i <= right && numElm >= 1; i++){
result.add(matrix[top][i]);
numElm--;
}
top++;
//右边层
for(int i = top; i <= bottom && numElm >= 1; i++){
result.add(matrix[i][right]);
numElm--;
}
right--;
//最下层
for(int i = right; i >= left && numElm >= 1; i--){
result.add(matrix[bottom][i]);
numElm--;
}
bottom--;
//最左层
for(int i = bottom; i >= top && numElm >= 1; i--){
result.add(matrix[i][left]);
numElm--;
}
left++;
}
return result;
}
}