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

โปรแกรม C++ พิมพ์เมทริกซ์แบบ Z Form


ที่นี่เราจะดูวิธีพิมพ์องค์ประกอบของเมทริกซ์ในรูปแบบ Z (Z form) ถ้าอาร์เรย์เป็นแบบด้านล่าง −

5 8 7 1
2 3 6 4
1 7 8 9
4 8 1 5

จะพิมพ์เป็น: 5, 8, 7, 1, 6, 7, 4, 8, 1, 5

อัลกอริทึม

printMatrixZ(mat)

Begin
    print the first row
    i := 1, j := n-2
    while i < n and j >= 0, do
        print mat[i, j]
        i := i + 1, j := j - 1
    done
    print the last row
End

ตัวอย่าง

#include<iostream>
#define MAX 4
using namespace std;

void printMatrixZ(int mat[][MAX], int n) {
    for(int i = 0; i < n; i++) {
        cout << mat[0][i] << " ";
    }
    int i = 1, j = n - 2;
    while(i < n && j >= 0) {
        cout << mat[i][j] << " ";
        i++;
        j--;
    }
    for(int i = 1; i < n; i++) {
        cout << mat[n-1][i] << " ";
    }
}

int main() {
    int matrix[][MAX] = {{5, 8, 7, 1},
                         {2, 3, 6, 4},
                         {1, 7, 8, 9},
                         {4, 8, 1, 5}};
    printMatrixZ(matrix, 4);
}

ผลลัพธ์

5 8 7 1 6 7 4 8 1 5