/************************************************************************/
/*
顺时针打印矩阵
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字
*/
/************************************************************************/
#include <iostream>
using namespace std;
#define N 4
#define M 5
void print_matrix(int matrix[][M], int len)
{
for (int i = 0; i < len; i++)
{
for (int j = 0; j < M; j++)
cout << matrix[i][j] << " ";
cout <<endl;
}
}
void print(int matrix[][M], int len)
{
print_matrix(matrix, N);
bool right, left, down, up;
right = left = down = up = false;//控制打印的方向
right = true;//开始默认是向右打印
int begin_x = 0;//可打印的行号的最小值
int begin_y = 0;//可打印列号的最小值
int end_x = len-1;//可打印的行号最大值
int end_y = M-1;//可打印的列号的最大值
int i, j;
while(begin_x <= end_x && begin_y <= end_y)
{
if (right)
{
for (j = begin_y; j <= end_y; j++)
cout << matrix[begin_x][j] << " ,";
right = false;
down = true;
begin_x++;
}
if (down)
{
for (i = begin_x; i <= end_x; i++)
cout << matrix[i][end_y] << " ,";
down = false;
left = true;
end_y--;
}
if (left)
{
for (j = end_y; j >= begin_y; j--)
cout << matrix[end_x][j] << " ,";
left = false;
up = true;
end_x--;
}
if (up)
{
for (i = end_x; i >= begin_x; i--)
cout << matrix[i][begin_y] << " ,";
up = false;
right = true;
begin_y++;
}
}
}
int main()
{
int matrix[N][M] = {
{
1,2,3,4,17
},
{
5,6,7,8,18
},
{
9,10,11,12,19
},
{
13,14,15,16,20
}
};
print(matrix, N);
return 0;
}
顺时针打印矩阵
最新推荐文章于 2012-09-07 10:14:52 发布