ภาพรวมปัญหา
ได้รับเมทริกซ์ 2 มิติ ต้องพิมพ์สมาชิกในลำดับเกลียวทวนเข็มนาฬิกา (Counter-clockwise Spiral) เริ่มจากมุมซ้ายบน ไปทิศทาง ล่าง → ขวา → บน → ซ้าย
ตัวอย่าง
Input: 2 4 6 1 7 9 5 0 3 Output: 2 1 5 0 3 9 7

ลำดับการเดินทาง: 1 → 5 → 9 → 13 → 14 → 15 → 16 → 12 → 8 → 4 → 3 → 2 → 6 → 10 → 11 → 7
วิธีแก้ปัญหา
ใช้ลูป 4 ลูป สำหรับแต่ละทิศทาง (ลง, ขวา, ขึ้น, ซ้าย) และปรับขอบเขตหลังแต่ละรอบ
ตัวอย่างโค้ด C++
#include <bits/stdc++.h>
using namespace std;
#define R 3
#define C 3
void printCounterClockwiseSpiral(int m, int n, int matrix[R][C]) {
int i, k = 0, l = 0;
int count = 0;
int total = m * n;
while (k < m && l < n) {
if (count == total) break;
// ลง (Left column)
for (i = k; i < m; ++i) {
cout << matrix[i][l] << " ";
count++;
}
l++;
if (count == total) break;
// ขวา (Bottom row)
for (i = l; i < n; ++i) {
cout << matrix[m - 1][i] << " ";
count++;
}
m--;
if (count == total) break;
// ขึ้น (Right column)
if (k < m) {
for (i = m - 1; i >= k; --i) {
cout << matrix[i][n - 1] << " ";
count++;
}
n--;
}
if (count == total) break;
// ซ้าย (Top row)
if (l < n) {
for (i = n - 1; i >= l; --i) {
cout << matrix[k][i] << " ";
count++;
}
k++;
}
}
}
int main() {
int mat[R][C] = {
{ 1, 2, 3 },
{ 4, 5, 6 },
{ 7, 8, 9 }
};
cout << "Counter Clockwise Spiral form of the matrix is:\n";
printCounterClockwiseSpiral(R, C, mat);
return 0;
}
ผลลัพธ์ (Output)
Counter Clockwise Spiral form of the matrix is: 1 4 7 8 9 6 3 2 5