8, according to the sub-array diagonal sequentially output

8, Title: sequentially output according to the sub-array diagonal

If the array:
. 1. 3 2
. 4. 5. 6
. 7. 8. 9
press the sub-sequence diagonal from top right to bottom left output array:
. 1 2. 4
. 3. 5. 7
. 6. 8. 9

The key ideas: for sub-diagonal, the row index respective elements are equal and a line, such as: each element of each row subscripts and the first sub-diagonals is 0, the second 1 , the m is m-1 ... is the last (m-1) + (n-1) = n + m-2

#include<stdio.h>
int main(){
	//测试用例:int a[3][4]={1,2,4,7,3,5,8,10,6,9,11,12};
	int a[n][m];
	int i, j;
	for(){
		此处省略输入n行m列矩阵的代码
	}
	
	//最外层循环表示输出行列下标和为 i的副对角线上的各元素
	
	//先输出上副三角形的元素
	for(i=0;i<=m-1;i++){					//******组成上副三角形的每一条副对角线的第一个元素都在第一行,故起始行标都为0******
		for(j=0;j<=n-1;j++){				//i=0;j<=n-1;意为从第0行到第n-1行
			if(i-j>=0){						//i为行列下标和,已知行标j,则i-j为列标,而列标不能为负数,即i-j要大于等于0
				printf("%d ", a[j][i-j]);
			}else{
				break;
			}
		}
	}
	
	//接着输出副下三角形的元素
	for(i=m;i<=n+m-2;i++){			//******组成下副三角形的每一条对角线的第一个元素都在第m-1列,但它们的起始行标随副对角线的不同而不同******
		for(j=i-(m-1);j<=n-1;j++){	//i为行列下标和,已知列标m-1,则i-(m-1)为起始行标
			if(i-j>=0){				//此处分析同上副三角形
				printf("%d ", a[j][i-j]);
			}else{
				break;
			}
		}
	}
	return 0;
} 
Published 16 original articles · won praise 0 · Views 325

Guess you like

Origin blog.csdn.net/NAU_LHT/article/details/104168358