输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:
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。
借用一个哥们的代码思路,做了一定的改进
#define Matrix_h 4 //随意定义的数字
#define Matrix_l 5
//int Mat[Matrix_h][Matrix_h];
typedef enum direction
{
right=0,
down=1,
left=2,
up=3
};
direction ChangeDirection(int dir)
{
switch(dir)
{
case right:
return down;
case down:
return left;
case left:
return up;
case up:
return right;
}
}
void clockwise(int Mat[Matrix_h][Matrix_l])
{
int i=0,j=0;
direction dir=right;
int PrintNum=0;
while(PrintNum<Matrix_h*Matrix_l)
{
switch(dir)
{
case right:
if ((Mat[i][j]!=-100)&&(j<Matrix_l))
{
printf("%d ",Mat[i][j]);
PrintNum++;
Mat[i][j]=-100; //把已经打印出来的数字赋值为一个矩阵中没有的数字
j++;
}
else
{
dir=ChangeDirection(dir);
j--; //运行结束后,j=Matrix_l+1,因此需要进行j--;
i++;//i进行跳入下一行。
}
break;
case down:
if ((Mat[i][j]!=-100)&&(i<Matrix_h))
{
printf("%d ",Mat[i][j]);
PrintNum++;
Mat[i][j]=-100;
i++;
}
else
{
dir=ChangeDirection(dir);
i--;
j--;
}
break;
case left:
if ((Mat[i][j]!=-100)&&(j>=0))
{
printf("%d ",Mat[i][j]);
PrintNum++;
Mat[i][j]=-100;
j--;
}
else
{
dir=ChangeDirection(dir);
j++;
i--;
}
break;
case up:
if ((Mat[i][j]!=-100)&&(i>=0))
{
printf("%d ",Mat[i][j]);
PrintNum++;
Mat[i][j]=-100;
i--;
}
else
{
dir=ChangeDirection(dir);
i++;
j++;
}
break;
}
}
}