假设我们有一个矩阵,并且必须以螺旋方式打印矩阵元素。首先,从第一行开始,先打印整个内容,然后再打印最后一列,然后再打印最后一行,依此类推,从而以螺旋方式打印元素。所以如果矩阵像-
1 | 2 | 3 | 4 | 5 | 6 |
7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18岁 |
然后输出将像[1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16]
为了解决这个问题,我们将遵循以下步骤-
currRow:= 0和currCol:= 0
而currRow和currCol在矩阵范围内
对于i:= n-1到currCol,执行
将m减1
如果currCol <n,则
展示垫[m-1,i]
展示垫[i,currCol]
对于i:= m-1到currRow,执行
将currCol增加1
展示垫[i,n-1]
展示垫[currRow,i]
对于范围currCol和n-1的i,
将currRow增加1
对于currRow和m-1范围内的i,执行
n减少1
如果currRow <m,则
让我们看下面的实现以更好地理解-
#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] [7,8,9,10,11,12] [13,14,15,16,17,18]]
输出结果
1 2 3 4 5 6 12 18 17 16 15 14 13 7 8 9 10 11 15 16