在这个问题上,我们得到一个二维矩阵。我们的任务是打印矩阵的锯齿形。
让我们以一个例子来了解问题
Input: 12 99 43 10 82 50 15 75 5 Output: 12 99 43 50 82 10 15 75 5
为了解决这个问题,我们将在两个方向(LtoR和RtoL)上打印数组的元素。并使用flag变量更改方向。
#include <iostream>
using namespace std;
void printZigZagPattern(int row, int col, int a[][5]) {
   int evenRow = 0;
   int oddRow = 1;
   while (evenRow<ow) {
      for (int i=0;i<col;i++) {
         cout<<a[evenRow][i]<<" ";
      }
      evenRow = evenRow + 2;
      if(oddRow < row) {
         for (int i=col-1; i>=0; i--)
            cout<<a[oddRow][i] <<" ";
      }
      oddRow = oddRow + 2;
   }
}
int main() {
   int r = 3, c = 3;
   int mat[][5] = {
      {12,99,43},
      {10,82,50},
      {15,75,5}
   };
   cout<<"Elements of the matrix in ZigZag manner :\n";
   printZigZagPattern(r , c , mat);
   return 0;
}输出结果
ZigZag方式的矩阵元素-
12 99 43 50 82 10 15 75 5