Matrix Zigzag Traversal
Given a matrix of m x n elements (m rows, ncolumns), return all elements of the matrix in ZigZag-order.
Have you met this question in a real interview?
Yes
Example
Given a matrix:
[
[1, 2, 3, 4],
[5, 6, 7, 8],
[9,10, 11, 12]
]
return [1, 2, 5, 9, 6, 3, 4, 7, 10, 11, 8, 12]
public class Solution {
/**
* @param matrix: a matrix of integers
* @return: an array of integers
*/
public int[] printZMatrix(int[][] matrix) {
int m = matrix.length;
int n = matrix[0].length;
int l = matrix.length*matrix[0].length;
int[] result = new int[l]; int d = -1;
int x = 0;
int y = 0;
for(int i=0;i<l;i++) {
result[i] = matrix[x][y]; if(x+d < 0 && y < n-1 || x+d >= m && y >= 0) {
d = -d;
y++;
}else {
if(y-d < 0 && x < m-1 || y-d >= n && x >= 0) {
d = -d;
x++;
}else {
x = x + d;
y = y - d;
}
}
} return result;
}
}