इस समस्या में, हमें एक 2-डायमेंशनल मैट्रिक्स दिया गया है। हमारा कार्य मैट्रिक्स का जिगजैग फॉर्म प्रिंट करना है।
उदाहरण
Input: 12 99 43 10 82 50 15 75 5 Output: 12 99 43 50 82 10 15 75 5
इस समस्या को हल करने के लिए, हम ऐरे के एलिमेंट्स को दोनों दिशाओं में प्रिंट करेंगे (LtoR और RtoL)। और फ्लैग वेरिएबल का उपयोग करके दिशा बदलेंगे।
उदाहरण
#include <iostream>
using namespace std;
void printZigZagPattern(int row, int col, int a[][5]) {
int evenRow = 0;
int oddRow = 1;
while (evenRow < row) {
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;
}
आउटपुट
Elements of the matrix in a ZigZag manner -
12 99 43 50 82 10 15 75 5