You are given a matrix ‘mat’ of ‘N’ rows and ‘M’ columns. Your task is to return the Zig-Zag order of the matrix.
The Zig-Zag order of a 5 x 5 matrix is given below

You are a given the matrix -:
‘mat’ = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Here the Zig-Zag order of the given matrix is [1, 2, 4, 7, 5, 3, 6, 8, 9]. Hence the answer is [1, 2, 4, 7, 5, 3, 6, 8, 9].
The first line of input contains a single integer ‘T’ representing the number of test cases.
The first line of each test case contains two space-separated integers, ‘N’ and ‘M’, representing the number of rows and columns of the matrix.
The next ‘N’ lines contain ‘M’ space-separated integers denoting the elements of the matrix ‘mat.’
Output Format:
For each test case, print N*M space-separated integers representing the Zig-Zag order of the matrix.
Print a separate line for each test case.
1 <= T <= 10
1 <= N, M <= 10^3
0 <= mat[i][j] <= 10^9
Time Limit: 1 sec
Note:
You do not need to print anything. It has already been taken care of. Just implement the function.
2
3 3
1 2 3
4 5 6
7 8 9
2 3
4 5 6
1 2 3
1 2 4 7 5 3 6 8 9
4 5 1 2 6 3
For the first test cases you are given,
‘mat’ = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Here the zigzag order of the given matrix is [1, 2, 4, 7, 5, 3, 6, 8, 9]. Hence the answer is [1, 2, 4, 7, 5, 3, 6, 8, 9].
For the second test cases you are given,
‘mat’ = [[4, 5, 6],
[1, 2, 3]]
Here the zigzag order of the given matrix is [4, 5, 1, 2, 6, 3]. Hence the answer is [4, 5, 1, 2, 6, 3].
2
4 4
7 6 0 2
8 4 6 5
3 4 0 4
5 4 6 3
4 2
0 5
1 4
2 6
9 4
7 6 8 3 4 0 2 6 4 5 4 0 5 4 6 3
0 5 1 2 4 6 9 4
Try to traverse the matrix according to the question.
In this approach, we traverse the given matrix diagonally and change the direction when we reach the corner of the matrix.
Each time we change the direction of the path, we will add a new diagonal path to the answer.
Algorithm:
O(N*M), Where N and M are the numbers of rows and columns of the matrix.
We are traversing through each element of the array, which will cost O(N*M) time. Hence the final time complexity is O(N*M).
O(N*M), Where N and M are the numbers of rows and columns of the matrix
We are maintaining an array to store the Zig-Zag path of the matrix that will have all the elements of the matrix. Hence the final space complexity is O(N*M).