이 문제에서는 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