顺时针输出数组

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字。
例如:如果输入如下矩阵:

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;
		}
	}




}


 

顺时针输出二维数组,可以按照以下步骤进行: 1. 初始化四个边界变量:top、bottom、left、right,分别表示当前输出的上边界、下边界、左边界和右边界。 2. 初始化一个变量dir,表示当前遍历的方向,初始值为0,表示向右遍历。 3. 使用一个循环,直到上边界大于下边界或左边界大于右边界为止: - 如果dir为0,依次输出上边界的元素,然后将上边界下移一行,即top加1。 - 如果dir为1,依次输出右边界的元素,然后将右边界左移一列,即right减1。 - 如果dir为2,依次输出下边界的元素,然后将下边界上移一行,即bottom减1。 - 如果dir为3,依次输出左边界的元素,然后将左边界右移一列,即left加1。 - 每次输出完一个边界后,需要更新dir的值为(dir+1)%4,以改变遍历的方向。 4. 完成遍历后即可得到顺时针输出的结果。 以下是使用Python实现的代码示例: ```python def clockwisePrint(matrix): if not matrix: return [] top, bottom = 0, len(matrix) - 1 left, right = 0, len(matrix[0]) - 1 dir = 0 res = [] while top <= bottom and left <= right: if dir == 0: for i in range(left, right + 1): res.append(matrix[top][i]) top += 1 elif dir == 1: for i in range(top, bottom + 1): res.append(matrix[i][right]) right -= 1 elif dir == 2: for i in range(right, left - 1, -1): res.append(matrix[bottom][i]) bottom -= 1 else: for i in range(bottom, top - 1, -1): res.append(matrix[i][left]) left += 1 dir = (dir + 1) % 4 return res ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值