欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

“之”字形打印矩阵

程序员文章站 2022-04-08 16:07:55
...

【题目】
给定一个矩阵martix,按照"之"字形的方式打印矩阵,如下

1 2 3 4
5 6 7 8
9 10 11 12

之字形打印结果为:1,2,5,9,6,3,4,7,10,11,8,12

“之”字形打印矩阵

#include <cstdio>
void printlevel(int martix[][4],int row1,int col1,int row2,int col2 ,bool fromup)//打印每个斜对角线
{
	if (fromup == 0)
	{
		while (row1 <= row2)
		{
			printf("%d ", martix[row1++][col1--]);
		}
	}
	else
	{
		while (row2>=row1)
		{
			printf("%d ", martix[row2--][col2++]);
		}
	}
}
void print(int martix[][4],int n,int m)//每次斜对角线打印完后判断打印方向以及边界
{
	int row1, col1, row2, col2;
	row1 = col1 = row2 = col2 = 0;
	int endr = n - 1, endc = m - 1;
	bool fromup = false;
	while (row1!=endr+1)
	{
		printlevel(martix, row1, col1, row2, col2, fromup);
		row1 = col1 == endc ? row1 + 1 : row1;
		col1 = col1 == endc ? col1 : col1 + 1;
		col2 = row2 == endr ? col2 + 1 : col2;
		row2 = row2 == endr ? row2 : row2 + 1;
		fromup = !fromup;
	}
	printf("\n");
}
int main()
{
	int martix[3][4];
	int count = 1;
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			martix[i][j] = count++;
		}
	}
	for (int i = 0; i < 3; i++)
	{
		for (int j = 0; j < 4; j++)
		{
			printf("%d ", martix[i][j]);
		}
		printf("\n");
	}
	print(martix, 3, 4);
	return 0;
}

“之”字形打印矩阵

相关标签: 个人学习笔记