054 螺旋矩阵
public class SpiralOrder054 {
public static void main(String[] args) {
// 正确顺序:123698745
int[][] matrix = new int[][]{{1,2,3},{4,5,6},{7,8,9}};
List<Integer> res = spiralOrder(matrix);
for(Integer order : res){
System.out.println(order);
}
}
public static List<Integer> spiralOrder(int[][] matrix) {
// 不需要一个flag标记位来表示遍历的方向,方向是固定的。边界可以由方向来决定
// List<Integer> res = new ArrayList<>();
// int width = matrix.length;//矩阵的行(宽度)
// int length = matrix[0].length;//矩阵的列(长度)
// int flag = 0;//0表示正序遍历行,1表示正序遍历列,-1表示倒序遍历行,-2表示倒序遍历列
// while(width > 0 && length > 0){
// int row = 0;// 每一圈遍历的行和列
// int col = 0;
// //先遍历行
// if(flag == 0){
// for(int i = col; i < width; i++){
// res.add(matrix[row][i]);
// }
// flag = 1; //第一行遍历完之后,开始正序遍历列
// width--; //第一行遍历完之后,下一次遍历行的时候宽度应该减1
// }
// if(flag == 1){
// for(int i = row; i < length; i++ ){
// res.add(matrix[i][col]);
// }
// flag = -1;
// length--;
// }
// }
List<Integer> res = new ArrayList<>();
int left = 0;
int top = 0;
int bottom = matrix.length-1;
int right = matrix[0].length-1;
//定义四个角表示边界
//那么遍历顺序应该是:
// (top,left)-->(top,right)
// (top+1,right)--->(bottom,right)
// (bottom,right-1)--->(bottom,left+1)
// (bottom,left)--->(top+1,left)
while(left <= right && top <= bottom){
for(int i = left; i <= right; i++){
res.add(matrix[top][i]);
}
for(int i = top+1; i <= bottom; i++){
res.add(matrix[i][right]);
}
if(left < right && top < bottom){
for(int i = right-1; i > left; i--){
res.add(matrix[bottom][i]);
}
for(int i = bottom; i > top; i--){
res.add(matrix[i][left]);
}
}
top++;
bottom--;
left++;
right--;
}
return res;
}
}