You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

矩阵从右上角开始的反向对角线遍历代码改写求助

矩阵右上角起始的Zigzag对角线遍历代码修改方案

需求说明

给定如下5行4列的矩阵:

1     2     3     4
5     6     7     8
9    10    11    12
13    14    15    16
17    18    19    20

需要实现从右上角(元素4)开始的Zigzag对角线遍历,预期输出为:

4
8 3
12 7 2
16 11 6 1
20 15 10 5
19 14 9
18 13
17

修改后的完整代码

class GFG {
    static final int ROW = 5;
    static final int COL = 4;
 
    static int min(int a, int b) {
        return (a < b) ? a : b;
    }
 
    static int min(int a, int b, int c) {
        return min(min(a, b), c);
    }
 
    static int max(int a, int b) {
         return (a > b) ? a : b;
    }
 
    static void diagonalOrder(int matrix[][]) {
        for (int line = 1; line <= (ROW + COL - 1); line++) {
            // 调整起始列:从右侧开始计算
            int start_col = min(COL - 1, line - 1);
            // 计算当前对角线的元素个数
            int count = min(line, (start_col + 1), ROW);
 
            for (int j = 0; j < count; j++) {
                // 调整行和列的索引,实现从右上到左下的对角线遍历
                System.out.print(matrix[min(ROW - 1, line - 1) - j][start_col - j] + " ");
            }
            System.out.println();
        }
    }
 
    public static void main(String[] args) {
        int M[][] = {
            { 1, 2, 3, 4 },
            { 5, 6, 7, 8 },
            { 9, 10, 11, 12 },
            { 13, 14, 15, 16 },
            { 17, 18, 19, 20 },
        };
 
        System.out.print("\nDiagonal printing of matrix is \n");
        diagonalOrder(M);
    }
}

关键改动说明

  1. 起始列计算:将原代码的start_col = max(0, line - ROW)改为start_col = min(COL - 1, line - 1),确保每一行的对角线起始列从矩阵右侧开始,逐步向左移动。
  2. 元素个数计算:将count = min(line, (COL - start_col), ROW)改为count = min(line, (start_col + 1), ROW),因为现在起始列是从右往左,可用的列数是start_col + 1(从0到start_col的列数)。
  3. 索引访问逻辑:将原代码的matrix[min(ROW, line)- j- 1][start_col + j]改为matrix[min(ROW - 1, line - 1) - j][start_col - j],实现从右上到左下的遍历方向,行索引逐步递增、列索引逐步递减。

内容的提问来源于stack exchange,提问作者Bence

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 00:50:27