int main()
{
int table[10][10];
int n,huong;
int dem;
int right,left,top,bottom;
cout << "Nhap vao cap cua mat ( 2 <= n <= 10): ";
cin >> n;
top = 0; left = 0;
right = n-1 ;bottom = n-1;
huong = 1;
dem = 1;
while ( dem <= n*n)
{
switch (huong)
{
case 1:
for(int i = left; i <= right; i++)
{
table[top][i] = dem++;
}
top ++;
huong = 2;
break;
case 2:
for(int i = top; i <= bottom; i++)
{
table[i][right] = dem++;
}
right --;
huong = 3;
break;
case 3:
for (int i = right; i >= 0; i--)
{
table[bottom][i] = dem++;
}
bottom --;
huong = 4;
break;
case 4:
for (int i = bottom; i <= top; i--)
{
table[i][left] = dem++;
}
left ++;
huong = 1;
break;
}
}
for(int i = 0; i < n; i++)
{
cout << endl;
for(int j = 0; j < n; j++)
cout << table[i][j];
}
return 0;
}
Mình dùng Switch case, giảm dòng, giảm cột để tạo hướng đi xoắn ốc theo chiều kim đồng hồ.
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?