ในปัญหานี้ เราได้รับเมทริกซ์ 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<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;
} ผลลัพธ์
องค์ประกอบของเมทริกซ์ในลักษณะซิกแซก -
12 99 43 50 82 10 15 75 5