Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

พิมพ์เมทริกซ์แบบ Zigzag ใน C++

ภาพรวมปัญหา

ได้รับเมทริกซ์ 2 มิติ ต้องพิมพ์ในรูปแบบ Zigzag คือ แถวคู่พิมพ์ซ้ายไปขวา แถวคี่พิมพ์ขวาไปซ้าย สลับกัน

ตัวอย่าง

Input:
12 99 43
10 82 50
15 75 5

Output: 12 99 43 50 82 10 15 75 5

วิธีแก้ปัญหา

ใช้ตัวแปร flag บอกทิศทางการพิมพ์ สลับทิศทางหลังพิมพ์แต่ละแถว

ตัวอย่างโค้ด C++

#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 += 2;
        
        // แถวคี่: ขวาไปซ้าย
        if (oddRow < row) {
            for (int i = col - 1; i >= 0; i--)
                cout << a[oddRow][i] << " ";
        }
        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;
}

ผลลัพธ์ (Output)

Elements of the matrix in a ZigZag manner:
12 99 43 50 82 10 15 75 5