輸入一個矩陣,按照從外向里以順時針的順序依次打印出每一個數字。例如,輸入如下矩陣:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
則依次打印出數字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10。
其實順時針的打印,無非就是先打印出矩陣最外面的第一行,然后是最后一列,然后是最后一行,最后是第一列,每一次打印時控制的條件也就是矩陣的行和列的邊界,那么打印完一圈之后只需要改變打印的范圍也就是首尾行和首尾列就可以再打印里面的矩陣;
程序設計如下:
#include <iostream>
#include <assert.h>
using namespace std;
void ClockwisePrintArr(int arr[][5], size_t row, size_t col)
{
assert(arr && row && col);//條件判斷
int (*tmp)[5] = arr;
//第一次開始的行為0,列也為0,打印終止的行為形參行數,列也為形參列數
int start_row = 0;
int start_col = 0;
int end_row = row;
int end_col = col;
//判斷條件當開始邊界小于終止邊界的時候
while((start_row < end_row) && (start_col < end_col))
{
//打印矩陣第一行
for(int i = start_col; i < end_col; ++i)
{
cout<<tmp[start_row][i]<<" ";
}
//打印矩陣最后一列
for(int i = start_row+1; i < end_row; ++i)
{
cout<<tmp[i][end_col-1]<<" ";
}
//打印矩陣最后一行
for(int i = end_col-2; i >= start_col; --i)
{
cout<<tmp[end_row-1][i]<<" ";
}
//打印矩陣第一列
for(int i = end_row-2; i > start_row; --i)
{
cout<<tmp[i][start_col]<<" ";
}
//依次將打印的邊界縮小一圈
++start_row;
++start_col;
--end_row;
--end_col;
}
cout<<endl;
}
int main()
{
int arr[5][5] = {{0, 1, 2, 3, 4},
{5, 6, 7, 8, 9},
{10, 11, 12, 13, 14},
{15, 16, 17, 18, 19},
{20, 21, 22, 23, 24}};
ClockwisePrintArr(arr, sizeof(arr)/sizeof(arr[0]), sizeof(arr[0])/sizeof(arr[0][0]));
return 0;
}運行程序:

《完》
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。