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

Print Matrix in Spiral Way (พิมพ์เมทริกซ์แบบเกลียว): อัลกอริทึมและโค้ดตัวอย่าง

อัลกอริทึมนี้ใช้พิมพ์สมาชิกของอาร์เรย์ในรูปแบบเกลียว (Spiral) เริ่มจากแถวแรก พิมพ์ทั้งแถว แล้วตามคอลัมน์สุดท้าย แล้วแถวสุดท้าย และทำซ้ำจนครบ

Time Complexity คือ O(M×N) โดย M = จำนวนแถว, N = จำนวนคอลัมน์

Input และ Output

Input: เมทริกซ์:
1  2  3  4  5  6
7  8  9 10 11 12
13 14 15 16 17 18

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

Algorithm

dispSpiral(mat, m, n)

Input: เมทริกซ์ mat, แถว m, คอลัมน์ n

Output: พิมพ์สมาชิกเมทริกซ์แบบเกลียว

Begin
    currRow := 0, currCol := 0
    while currRow และ currCol อยู่ในขอบเขตเมทริกซ์ do
        for i from currCol to n-1 do
            display mat[currRow, i]
        done
        currRow := currRow + 1
        for i from currRow to m-1 do
            display mat[i, n-1]
        done
        n := n - 1
        if currRow < m then
            for i from n-1 down to currCol do
                display mat[m-1, i]
            done
            m := m - 1
        if currCol < n then
            for i from m-1 down to currRow do
                display mat[i, currCol]
            done
            currCol := currCol + 1
    done
End

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

#include <iostream>
#define ROW 3
#define COL 6
using namespace std;

int array[ROW][COL] = {
    {1, 2, 3, 4, 5, 6},
    {7, 8, 9, 10, 11, 12},
    {13, 14, 15, 16, 17, 18}
};

void dispSpiral(int m, int n) {
    int i, currRow = 0, currCol = 0;
    while (currRow < ROW && currCol < COL) {
        for (i = currCol; i < n; i++) {
            cout << array[currRow][i] << " ";
        }
        currRow++;
        for (i = currRow; i < m; ++i) {
            cout << array[i][n-1] << " ";
        }
        n--;
        if (currRow < m) {
            for (i = n-1; i >= currCol; --i) {
                cout << array[m-1][i] << " ";
            }
            m--;
        }
        if (currCol < n) {
            for (i = m-1; i >= currRow; --i) {
                cout << array[i][currCol] << " ";
            }
            currCol++;
        }
    }
}

int main() {
    dispSpiral(ROW, COL);
}

Output

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