LeetCode--54. Spiral Matrix

灰太狼 2022-08-21 13:49 239阅读 0赞

Problem:

  1. Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in spiral order.
  2. For example,
  3. Given the following matrix:
  4. [
  5. [ 1, 2, 3 ],
  6. [ 4, 5, 6 ],
  7. [ 7, 8, 9 ]
  8. ]
  9. You should return [1,2,3,6,9,8,7,4,5].
  10. Subscribe to see which companies asked this question

Analysis:

  1. 题目理解:
  2. 将一维或二维数组中的元素按顺时针放向进行打印;
  3. 解题分析:
  4. 1. 模拟;
  5. 2. 递归:
  6. 1)每次重新计算最开始的左上初始点;
  7. 2)然后依此遍历最上一行,最右一列,最后一行,以及最左一行;
  8. 3)注意避免重复遍历,处理好边界问题;

Answer:
递归解法:

  1. public class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> list = new ArrayList<Integer>();
  4. if(matrix.length==0 || matrix[0].length==0) return list;
  5. int m = matrix.length, n = matrix[0].length;
  6. spiral_print(0,m-1,0,n-1,matrix,list);
  7. return list;
  8. }
  9. public static void spiral_print(int row_start,int row_end,int col_start,int col_end,int[][] matrix,List<Integer> list){
  10. if (row_start>row_end || col_start>col_end) return;
  11. for(int i=col_start;i<=col_end;i++){
  12. list.add(matrix[row_start][i]);
  13. }
  14. if(row_start+1>row_end) return;
  15. for(int i=row_start+1;i<=row_end;i++){
  16. list.add(matrix[i][col_end]);
  17. }
  18. if(col_start+1>col_end) return;
  19. for(int i=col_end-1;i>=col_start;i--){
  20. list.add(matrix[row_end][i]);
  21. }
  22. for(int i=row_end-1;i>row_start;i--){
  23. list.add(matrix[i][col_start]);
  24. }
  25. spiral_print(row_start+1,row_end-1,col_start+1,col_end-1,matrix,list);
  26. }
  27. }

迭代解法:

  1. public class Solution {
  2. public List<Integer> spiralOrder(int[][] matrix) {
  3. List<Integer> result = new ArrayList<Integer>();
  4. if(matrix.length == 0) return result;
  5. int left=0,right=matrix[0].length-1,top=0,bottom=matrix.length-1,direction=0;
  6. while(left <= right && top <= bottom){
  7. if(direction == 0){
  8. for(int i=left;i<= right;i++){
  9. result.add(matrix[top][i]);
  10. }
  11. top++;
  12. }
  13. else if(direction == 1){
  14. for(int i=top;i<=bottom;i++){
  15. result.add(matrix[i][right]);
  16. }
  17. right--;
  18. }
  19. else if(direction == 2){
  20. for(int i=right;i>=left;i--){
  21. result.add(matrix[bottom][i]);
  22. }
  23. bottom--;
  24. }
  25. else if(direction == 3){
  26. for(int i=bottom;i>=top;i--){
  27. result.add(matrix[i][left]);
  28. }
  29. left++;
  30. }
  31. direction=(direction+1) % 4;
  32. }
  33. return result;
  34. }
  35. }

发表评论

表情:
评论列表 (有 0 条评论,239人围观)

还没有评论,来说两句吧...

相关阅读