Given an m x n
matrix mat
, return an array of all the elements of the array in a diagonal order.
Example 1:
Input: mat = [[1,2,3],[4,5,6],[7,8,9]] Output: [1,2,4,7,5,3,6,8,9]
Example 2:
Input: mat = [[1,2],[3,4]] Output: [1,2,3,4]
Constraints:
m == mat.length
n == mat[i].length
1 <= m, n <= 104
1 <= m * n <= 104
-105 <= mat[i][j] <= 105
class Solution:
def findDiagonalOrder(self, mat: List[List[int]]) -> List[int]:
m, n = len(mat), len(mat[0])
ans, t = [], []
for i in range(m + n):
r = 0 if i < n else i - n + 1
c = i if i < n else n - 1
while r < m and c >= 0:
t.append(mat[r][c])
r += 1
c -= 1
if i % 2 == 0:
t.reverse()
ans.extend(t)
t.clear()
return ans
class Solution {
public int[] findDiagonalOrder(int[][] mat) {
int m = mat.length, n = mat[0].length;
int[] ans = new int[m * n];
int k = 0;
List<Integer> t = new ArrayList<>();
for (int i = 0; i < m + n - 1; ++i) {
int r = i < n ? 0 : i - n + 1;
int c = i < n ? i : n - 1;
while (r < m && c >= 0) {
t.add(mat[r][c]);
++r;
--c;
}
if (i % 2 == 0) {
Collections.reverse(t);
}
for (int v : t) {
ans[k++] = v;
}
t.clear();
}
return ans;
}
}
class Solution {
public:
vector<int> findDiagonalOrder(vector<vector<int>>& mat) {
int m = mat.size(), n = mat[0].size();
vector<int> ans;
vector<int> t;
for (int i = 0; i < m + n; ++i)
{
int r = i < n ? 0 : i - n + 1;
int c = i < n ? i : n - 1;
while (r < m && c >= 0)
{
t.push_back(mat[r][c]);
++r;
--c;
}
if (i % 2 == 0) reverse(t.begin(), t.end());
for (int v : t) ans.push_back(v);
t.clear();
}
return ans;
}
};
func findDiagonalOrder(mat [][]int) []int {
m, n := len(mat), len(mat[0])
var ans []int
for i := 0; i < m+n; i++ {
var t []int
r, c := i-n+1, n-1
if i < n {
r, c = 0, i
}
for r < m && c >= 0 {
t = append(t, mat[r][c])
r += 1
c -= 1
}
if i%2 == 0 {
p, q := 0, len(t)-1
for p < q {
t[p], t[q] = t[q], t[p]
p++
q--
}
}
for _, v := range t {
ans = append(ans, v)
}
}
return ans
}