---
# System prepended metadata

title: 0498. Diagonal Traverse
tags: [Leetcode, FaceBook, Medium]

---

# 0498. Diagonal Traverse
###### tags: `Leetcode` `Medium` `FaceBook`
Link: https://leetcode.com/problems/diagonal-traverse/
## 思路
就模拟一遍就好了
有一点点复杂
**要注意的是从不同的边出去，处理的方式不一样** 是根据边区分的
## Code
```java=
class Solution {
    public int[] findDiagonalOrder(int[][] mat) {
        int[] ans = new int[mat.length*mat[0].length];
        int m = mat.length;
        int n = mat[0].length;
        int r = 0;
        int c = 0;
        int idx = 0;
        int direction = 1;
        while(true){
            ans[idx++] = mat[r][c];
            if(r==mat.length-1 && c==mat[0].length-1) break;
            if(direction == 1){
                r -= 1;
                c += 1;
                if(r < 0 && c!=mat[0].length){
                    r = 0;
                    direction = -1;
                }
                if(c == mat[0].length){
                    r += 2;
                    c -= 1;
                    direction = -1;
                }
            }
            else{
                r += 1;
                c -= 1;
                if(c < 0 && r!=mat.length){
                    c = 0;
                    direction = 1;
                }
                if(r == mat.length){
                    c += 2;
                    r -= 1;
                    direction = 1;
                }
            }
        }
        return ans;
    }
}
```