Sunday, July 19, 2015

Matrix Zigzag Traversal

Matrix Zigzag Traversal

22%
Accepted
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) {
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0) return null;
        int m = matrix.length, n = matrix[0].length;
        int[] res = new int[m*n];
        int j = 0;
        for(int i = 0; i < m + n - 1; i++){
            if(i % 2 == 1){
                for(int y = Math.min(i, n - 1); y >= Math.max(0, i - m + 1); y--){
                    res[j++] = matrix[i-y][y];
                }
            } else{
                for(int x = Math.min(i, m - 1); x >= Math.max(0, i - n + 1); x--){
                    res[j++] = matrix[x][i-x];
                }
            }
        }
        return res;
    }
}

No comments:

Post a Comment