以螺旋方式打印矩阵\n


此算法用于以螺旋方式打印数组元素。首先从第一行开始,打印整个内容,然后打印最后一列,然后是最后一行,依此类推,因此以螺旋方式打印元素。 

此算法的时间复杂度为 O(MN),其中 M 是行数,N 是列数。

输入输出

Input:
The matrix:
 1   2   3   4   5   6
 7   8   9  10  11  12
13  14  15  16  17  18

Output:
Contents of an array as the spiral form
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16

算法

dispSpiral(mat, m, n)

输入:矩阵 mat,行和列 m 和 n。

输出:以螺旋方式打印矩阵的元素。

Begin
   currRow := 0 and currCol := 0
   while currRow and currCol are in the matrix range, do
      for i in range currCol and n-1, do
         display mat[currRow, i]
      done

      increase currRow by 1
      for i in range currRow and m-1, do
         display mat[i, n-1]
      done

      decrease n by 1
      if currRow < m, then
         for i := n-1 down to currCol, do
            display mat[m-1, i]
         done
         decrease m by 1
      if currCol < n, then
         for i := m-1 down to currRow, do
            display mat[i, currCol]
         done
         increase currCol by 1
   done
End

示例

#include <iostream>
#define ROW 3
#define COL 6
using namespace std;

int array[ROW][COL] = {
   {1, 2, 3, 4, 5, 6},
   {7, 8, 9, 10, 11, 12},
   {13, 14, 15, 16, 17, 18}
};

void dispSpiral(int m, int n) {
   int i, currRow = 0, currCol = 0;
   while (currRow < ROW && currCol <COL) {
      for (i = currCol; i < n; i++) {          //print the first row normally
         cout << array[currRow][i]<<" ";
      }
      currRow++;           //point to next row

      for (i = currRow; i < m; ++i) {       //Print the last column
         cout << array[i][n-1]<<" ";
      }

      n--;               //set the n-1th column is current last column

      if ( currRow< m) {         //when currRow is in the range, print the last row
         for (i = n-1; i >= currCol; --i) {
            cout << array[m-1][i]<<" ";
         }
         m--; //decrease the row range
      }

      if (currCol <n) {      //when currCol is in the range, print the fist column
         for (i = m-1; i >= currRow; --i) {
            cout << array[i][currCol]<<" ";
         }
         currCol++;
      }
   }
}

int main() {
   dispSpiral(ROW, COL);
}

输出

1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16

更新于: 17-Jun-2020

987 浏览

开启您的 职业生涯

完成课程并获得认证

开始
广告