剑指 Offer之顺时针打印矩阵(C++/Java双重实现)

1.问题描述

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
示例 1:
输入:matrix = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,3,6,9,8,7,4,5]
示例 2:
输入:matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
输出:[1,2,3,4,8,12,11,10,9,5,6,7]
限制:
0 <= matrix.length <= 100
0 <= matrix[i].length <= 100

2.问题分析

主要在上下左右设置四个界限,在每一次遍历的时候对界限进行相应的操作,就可以解出本题

3.代码实现

3.1C++代码

class Solution {
public:
    vector<int> spiralOrder(vector<vector<int>>& matrix) {
      /*判断是否为空*/
      if(matrix.size() == 0 || matrix[0].size() == 0) return {};
      /*设置上下左右四个界限*/
      vector<int> res; /*存储遍历结果*/
      int top = 0;
      int bottom = matrix.size() - 1;
      int left = 0;
      int right = matrix[0].size() - 1;
      /*此算法模拟顺时针输出的过程,请联想打印过程*/
      while(true)
      {
          /*1.top行从左到右遍历*/
          for(int i=left;i<=right;i++){
              res.push_back(matrix[top][i]);
          }
          /*top移动至下一行,并进行边界检测*/
          top++;
          if(top > bottom ) break;

          /*2.right列从上到下遍历*/
          for(int i=top;i<=bottom;i++){
              res.push_back(matrix[i][right]);
          }
          /*right左移,并进行边界检测*/
          right--;
          if(right < left) break;
          
          /*3.bottom行从右往左遍历*/
          for(int i = right;i>=left;i--){
              res.push_back(matrix[bottom][i]);
          }
          /*bottom行上移,并进行边界检测*/
          bottom -- ;
          if(bottom < top) break;
          /*4.left列从下往上遍历*/
          for(int i=bottom;i>=top;i--){
              res.push_back(matrix[i][left]);
          }
          /*left右移,并进行边界检测*/
          left++;
          if(left > right) break;
      }
      /*返回遍历结果*/
      return res;
    }
};

3.2Java代码

class Solution {
    public int[] spiralOrder(int[][] matrix) {
        if(matrix.length==0)
        return new int [0];
        int arr[]=new int[matrix.length*matrix[0].length];
        int top=0;
        int bottom=matrix.length-1;
        int left=0;
        int right=matrix[0].length-1;
        int cnt=0;
        while(true)
        {
            for(int i=left;i<=right;i++)
            {
                arr[cnt++]=matrix[top][i];
            }
            top++;
            if(top>bottom)
            break;
            for(int i=top;i<=bottom;i++)
            {
                arr[cnt++]=matrix[i][right];
            }
            right--;
           if (right<left)
            break;
            for(int i=right;i>=left;i--)
            {
                arr[cnt++]=matrix[bottom][i];
            }
            bottom--;
            if(bottom<top)
            break;
            for(int i=bottom;i>=top;i--)
            {
                arr[cnt++]=matrix[i][left];
            }
            left++;
            if(left>right)
            break;
        }
        return arr;

    }
}

猜你喜欢

转载自blog.csdn.net/qq_45737068/article/details/107725675