在C ++中以Z字形打印给定矩阵
在这个问题上,我们得到一个二维矩阵。我们的任务是打印矩阵的锯齿形。
让我们以一个例子来了解问题
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
热门推荐
10 小红书平安祝福语简短
11 生日祝福语大全女孩简短
12 收生日红包祝福语 简短
13 领证幽默祝福语简短
14 法考面试祝福语简短
15 老哥出门祝福语简短语
16 送灯祝福语简短独特
17 幼儿狗年祝福语大全简短
18 好听的元旦简短祝福语