[Algo] Print Matrix Diagonal 对角打印
Print Matrix Diagonal
Print the matrix in diagonal way. For example:
1 2 3 45 6 7 8
Print:
12 56 34 78
双重循环
复杂度
时间 O(NM) 空间 O(1)
思路
总共需要打印的层数,是长度加宽度减去一。关键在于内层的row = i - j
,而col = j
。
代码
private static void printDiagonal(int[][] matrix){ int m = matrix.length; int n = matrix[0].length; // 计算打印的层数 int lvl = m + n - 1; for(int i = 0; i < lvl; i++){ for(int j = i; j >= 0; j--){int row = i - j;int col = j;// 超过边界的点直接跳过if(row >= m || col >= n) continue;System.out.print(matrix[row][col]+" "); } System.out.println(); }}