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

พิมพ์เมทริกซ์สลับทิศทางซ้าย-ขวา ใน C++

ภาพรวมปัญหา

ได้รับอาร์เรย์ 2D ต้องพิมพ์สมาชิกเริ่มจากแถวแรก ซ้ายไปขวา แถวถัดไปขวาไปซ้าย สลับกันไปเรื่อยๆ

ตัวอย่าง

Input: array = { {2, 5}, {4, 9} }
Output: 2 5 9 4

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

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

Time Complexity: O(R×C)

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

#include <iostream>
using namespace std;

#define R 3
#define C 3

void printAlternateMatrix(int arr[R][C]) {
    bool direction = true;
    for (int i = 0; i < R; i++) {
        if (direction) {
            for (int j = 0; j < C; j++)
                printf("%d ", arr[i][j]);
        } else {
            for (int j = C - 1; j >= 0; j--)
                printf("%d ", arr[i][j]);
        }
        direction = !direction;
    }
}

int main() {
    int arr[][C] = {
        { 23, 50, 4 },
        { 89, 9, 34 },
        { 75, 1, 61 }
    };
    cout << "Matrix in alternate order is:\n";
    printAlternateMatrix(arr);
    return 0;
}

ผลลัพธ์ (Output)

The matrix in alternate order is:
23 50 4 34 9 89 75 1 61