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

พิมพ์เมทริกซ์แบบเกลียวจากจุดที่กำหนดใน C++

ภาพรวมปัญหา

ได้รับเมทริกซ์ 2D และจุด P(c,r) ต้องพิมพ์สมาชิกทั้งหมดในลำดับเกลียวทวนเข็มนาฬิกา (Anti-clockwise) เริ่มจากจุด P

ตัวอย่าง

Input: matrix[][] = {{3, 5, 7}} 
Output: (ขึ้นอยู่กับจุดเริ่มต้น)

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

ใช้ลูป 4 ลูปสำหรับการพิมพ์แต่ละทิศทาง เริ่มจากจุด P และขยายไปแบบเกลียว

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

#include <iostream>
using namespace std;

const int MAX = 100;

void printSpiralMatrix(int mat[][MAX], int r, int c) {
    int i, a = 0, b = 2;
    int low_row = (0 > a) ? 0 : a;
    int low_column = (0 > b) ? 0 : b - 1;
    int high_row = ((a + 1) >= r) ? r - 1 : a + 1;
    int high_column = ((b + 1) >= c) ? c - 1 : b + 1;
    
    while ((low_row > 0 - r && low_column > 0 - c)) {
        for (i = low_column + 1; i <= high_column && i < c && low_row >= 0; ++i)
            cout << mat[low_row][i] << " ";
        low_row -= 1;
        
        for (i = low_row + 2; i <= high_row && i < r && high_column < c; ++i)
            cout << mat[i][high_column] << " ";
        high_column += 1;
        
        for (i = high_column - 2; i >= low_column && i >= 0 && high_row < r; --i)
            cout << mat[high_row][i] << " ";
        high_row += 1;
        
        for (i = high_row - 2; i > low_row && i >= 0 && low_column >= 0; --i)
            cout << mat[i][low_column] << " ";
        low_column -= 1;
    }
    cout << endl;
}

int main() {
    int mat[][MAX] = {
        { 1, 4, 7 },
        { 2, 5, 8 },
        { 3, 6, 9 }
    };
    int r = 3, c = 3;
    cout << "Spiral traversal of matrix starting from point " << r << ", " << c << " is:\n";
    printSpiralMatrix(mat, r, c);
    return 0;
}

ผลลัพธ์ (Output)

Spiral traversal of matrix starting from point 3, 3 is:
7 8 5 4 9 6 3 2 1