498.对角线遍历 模拟矩阵扫描 Python&Java解题

498.对角线遍历

https://leetcode.cn/problems/diagonal-traverse/solution/by-qingfengpython-h6zl/

难度:中等

题目:

给你一个大小为 m x n 的矩阵 mat ,请以对角线遍历的顺序,用一个数组返回这个矩阵中的所有元素。

提示:

  • m == mat.length
  • n == mat[i].length
  • 1 <= m, n <= 104
  • 1 <= m * n <= 104
  • -10^5 <= mat[i][j] <= 10^5

示例:

示例 1:

输入:mat = [[1,2,3],[4,5,6],[7,8,9]]
输出:[1,2,4,7,5,3,6,8,9]
示例 2:

输入:mat = [[1,2],[3,4]]
输出:[1,2,3,4]

分析

一道逻辑比较简单的模拟题目,可以不必考虑太多,仅关注 移动方向、边界 这两个问题即可。

  1. 起始点为row,col = [0,0],这个很明确
  2. 矩阵扫描的方向有两个[(1, -1), (-1, 1)],即左下↙,和右上↗。
  3. 扫描方向为右上↗,且坐标处于矩阵顶部和右边界时,当col未抵达右边界时,向右走一格,否则则向下走一格,并且转向左下↙
  4. 扫描方向为左下↙,且坐标处于矩阵左边界和底部时,当row未抵达底部时,向下走一格,否则向右走一格,并且转向右上↗
  5. 循环执行3、4,直至走到矩阵末端结束循环即可。

[图片上传失败...(image-77cac8-1662294937592)]

解题:

Python:

class Solution:
    def findDiagonalOrder(self, mat):
        choice = [(1, -1), (-1, 1)]
        row, col, row_max, col_max, direction = 0, 0, len(mat), len(mat[0]), 1
        ret = []
        while row < row_max and col < col_max:
            ret.append(mat[row][col])
            if direction == 1 and (row == 0 or col == col_max - 1):
                direction = 0
                if col < col_max - 1:
                    col += 1
                else :
                    row += 1
            elif direction == 0 and (col == 0 or row == row_max - 1):
                direction = 1
                if row < row_max - 1:
                    row += 1
                else :
                    col += 1
            else:
                row += choice[direction][0]
                col += choice[direction][1]
        return ret

Java:

class Solution {
    public int[] findDiagonalOrder(int[][] mat) {
        int row = 0, col = 0, row_max = mat.length, col_max = mat[0].length;
        int index = 0, direction = 1;
        int[][] choice = {{1, -1}, {-1, 1}};
        int[] ret = new int[row_max * col_max];
        while (row < row_max && col < col_max) {
            ret[index++] = mat[row][col];
            if (direction == 1 && (row == 0 || col == col_max - 1)) {
                direction = 0;
                if (col < col_max - 1) {
                    col++;
                } else {
                    row++;
                }
            } else if (direction == 0 && (col == 0 || row == row_max - 1)) {
                direction = 1;
                if (row < row_max - 1) {
                    row++;
                } else {
                    col++;
                }
            } else {
                row += choice[direction][0];
                col += choice[direction][1];
            }
        }
        return ret;
    }
}

欢迎关注我的公_众号: 清风Python,带你每日学习Python算法刷题的同时,了解更多python小知识。

我的个人博客:https://qingfengpython.cn

力扣解题合集:https://github.com/BreezePython/AlgorithmMarkdown

你可能感兴趣的:(498.对角线遍历 模拟矩阵扫描 Python&Java解题)