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

พิมพ์เมทริกซ์ในรูปแบบ Anti-spiral

ได้รับอาร์เรย์ 2D ขนาด n*n ต้องหาการจัดเรียงแบบ antispiral ของเมทริกซ์ที่กำหนด

Input: arr[4][4] = {1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16}
Output: 10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1

อัลกอริทึม

START
STEP 1 -> declare stack vector element as stk and variables as int r=4, c=4, i, j, rs=0 and cs=0
Step 2 -> store matrix elements in 2D array
Step 3 -> Loop For i=0 and i<4 and i++
    Loop For j=0 and j<4 and j++
        Print arr[i][j]
    End
    Print \n
End
Step 4 -> Loop While rs=rs and --i
            Push arr[r-1][i]
        End
        r--
    End
    IF(rs=cs and i--
            Push arr[i][rs]
        End
        rs++
    End
End
Step 5 -> Loop While !stk.empty()
    Print stk.top()
    Call pop()
End
STOP

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

#include <iostream>
#include <bits/stdc++.h>
using namespace std;

int main() {
    stack stk;
    int R=4, C=4, i, j, RS=0, CS=0;
    int mat[R][C] = {{1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16}};
    for (i=0; i<4; i++) {
        for (j=0; j<4; j++)
            cout << mat[i][j] << " ";
        cout << "\n";
    }
    while (RS < C && CS < R) {
        for (i=RS; i=RS; --i)
                stk.push(mat[R-1][i]);
            R--;
        }
        if (RS < C) {
            for (i=C-1; i>=CS; i--)
                stk.push(mat[i][RS]);
            RS++;
        }
    }
    while (!stk.empty()) {
        cout << stk.top() << " ";
        stk.pop();
    }
}

ผลลัพธ์

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
10 11 7 6 5 9 13 14 15 16 12 8 4 3 2 1