C++ 中的螺旋矩阵
假设我们有一个矩阵,我们必须以螺旋方式打印矩阵元素。首先从第一行开始,打印全部内容,然后沿着最后一列打印,最后沿着最后一行打印,诸如此类,最终以螺旋方式打印元素。如果矩阵为 -
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 在 currCol 和 n-1 的范围内,
显示 mat[currRow, i]
增加 currRow 1
对于 i 在 currRow 和 m-1 的范围内,
显示 mat[i, n-1]
减少 n 1
如果 currRow < m,那么
对于 i 从 n-1 到 currCol,
显示 mat[m-1, i]
减少 m 1
如果 currCol < n,那么
对于 i 从 m-1 到 currRow,
显示 mat[i, currCol]
增加 currCol 1
示例 (C++)
让我们看看以下实现,以便更好地理解 -
#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
广告