1 2 3
4 5 6
7 8 9
输出
3
2 6
1 5 9
4 8
7
按对角线将矩阵分为右上角和左下角。右上角:起点row = 0, col = n - 1 ~ 0, 相邻元素间行和列相差1;右下角:起点col = 0, row = 0 ~ n - 1,相邻元素间行和列相差1,复杂度O(n2)
static void printMatrix(int[][] a)
{
int rowLen = a.length;
int colLen = a[0].length;
for(int i = colLen - 1; i >= 0 ; i--)//右上角row = 0, col = colLen - 1 ~ 0;
{
int row = 0;
int col = i;
while(row >= 0 && row < rowLen && col >= 0 && col < colLen)
{
System.out.print(a[row][col]);
row++;
col++;
}
System.out.println();
}
for(int i = 1; i < rowLen; i++)//左下角col = 0, row = 1 ~ rowLen - 1;
{
int row = i;
int col = 0;
while(row >= 0 && row < rowLen && col >= 0 && col < colLen)
{
System.out.print(a[row][col]);
row++;
col++;
}
System.out.println();
}
}