lintcode-easy-Matrix Zigzag Traversal

Given a matrix of m x n elements (m rows, n columns), return all elements of the matrix in ZigZag-order.

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) {
        // write your code here
        if(matrix == null || matrix.length == 0 || matrix[0] == null || matrix[0].length == 0)
            return new int[0];
        
        int m = matrix.length;
        int n = matrix[0].length;
        
        int i = 0; 
        int j = 0;
        boolean up = true;
        
        int[] result = new int[m * n];
        
        for(int k = 0; k < m * n; k++){
            result[k] = matrix[i][j];
            
            if(up){
                if(i - 1 >= 0 && j + 1 < n){
                    i--;
                    j++;
                }
                else{
                    if(i - 1 < 0 && j + 1 < n){
                        j++;
                        up = false;
                    }
                    else{
                        i++;
                        up = false;
                    }
                }
            }
            else{
                if(i + 1 < m && j - 1 >= 0){
                    i++;
                    j--;
                }
                else{
                    if(j - 1 < 0 && i + 1 < m){
                        i++;
                        up = true;
                    }
                    else{
                        j++;
                        up = true;
                    }
                }
            }
        }
        
        return result;
    }
}

 

posted @ 2016-02-27 07:53  哥布林工程师  阅读(193)  评论(0编辑  收藏  举报