代码:
public class Solution { public List<Integer> spiralOrder(int[][] matrix) { List<Integer> resultList = new ArrayList<>(); int row = matrix.length; if(row == 0) return resultList; int col = matrix[0].length; if(col == 0) return resultList; int n = row < col? row : col; for(int i = 0; i <= n/2; i++){ int width = col - 1 - 2*i; int height = row - 1 - 2*i; if(width < 0 || height < 0) break; if(height == 0 && width == 0){ resultList.add(matrix[i][i]); break; } if(height == 0) { for(int j = 0; j <= width; j++) resultList.add(matrix[i][i+j]); break; } if(width == 0){ for(int j = 0; j <= height; j++) resultList.add(matrix[i+j][i]); break; } for(int j = 0; j < (width+height)*2; j++){ if(j < width) resultList.add(matrix[i][i+j]); else if(j < width+height && j >= width) resultList.add(matrix[i+j-width][i+width]); else if(j < 2*width+height && j >= width+height) resultList.add(matrix[i+height][i+width-(j-width-height)]); else resultList.add(matrix[i+height-(j-2*width-height)][i]); /* int top_left = matrix[i][i]; int top_right = matrix[i][i+num]; int bottom_right = matrix[i+num][i+num]; int bottom_left = matrix[i+num][i]; */ } } return resultList; } }
时间: 2024-11-19 07:20:34