您的位置:首页 > 其它

顺时针打印矩阵

2014-04-29 22:49 330 查看
输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。

例如:输入矩阵

{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

代码如下:

typedef int (*Mystype)[4];//定义一个指向有4个int型数值的数组的指针,用来传递二维数组。这里的4是你输入矩阵的列数。

void PrintMatrixCir(Mystype numbers ,int columns , int rows , int start);
void PrintMatrixClockwisely(Mystype numbers ,int columns , int rows)
{
if (numbers == NULL || columns <= 0 || rows <= 0)
{
return;
}
int start = 0 ;//start表示圈数
while (columns > start*2 && rows > start*2)// 满足条件就输出一圈
{
PrintMatrixCir(numbers ,columns ,rows , start);
start++;
}

}
void PrintMatrixCir(Mystype numbers ,int columns , int rows , int start)
{
if (numbers == NULL || columns <= 0 || rows <= 0 || start < 0)
{
return;
}
int endX = columns - 1 - start ;
int endY = rows - 1 - start ;
if (start <= endX)//第一步,从左向右输出一行
{
for (int i = start ; i<= endX ;i++)
{
cout<<numbers[start][i]<<" ";
}
}
if (start < endY)//第二步,从上向下输出一列
{
for (int i = start + 1 ;i <= endY ; i++)
{
cout<<numbers[i][endX]<<" ";
}
}
if (start < endX && start <endY)//第三步,从右向左输出一行
{
for (int i = endX-1 ; i>=start ;i--)
{
cout<<numbers[endY][i]<<" ";
}
}
if (start < endX && start <endY-1)//第四步,从下向上输出一列
{
for (int i= endY - 1 ; i>= start+1 ; i--)
{
cout<<numbers[i][start]<<" ";
}
}

}

int main()
{
int numbers[4][4] = {
{1,    2,   3,   4 },
{5,    6,   7,   8 },
{9,   10,  11,  12 },
{13,  14,  15,  16 }
} ;

Mystype p = numbers;
PrintMatrixClockwisely( p ,4 , 4 );
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: