Problem

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

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]

Note

Z字形走法,从左下到右上,右移或下移一位,再从右上到左下,下移或右移一位,如此往复。
注意两点:

  1. 两个while循环必须是先走斜上的循环,再走斜下的循环

  2. 两个while循环之后的平移操作,有着严格的相对顺序斜上之后的平移,先考虑右移,再考虑下移;斜下之后的平移,先考虑下移,再考虑右移。

Solution

public class Solution {
    public int[] printZMatrix(int[][] matrix) {
        if (matrix == null) return null;
        int m = matrix.length, n = matrix[0].length, count = m * n;
        int[] res = new int[count];
        res[0] = matrix[0][0];
        int i = 1, r = 0, c = 0;
        while (i < count) {
            while (r-1 >= 0 && c+1 < n) res[i++] = matrix[--r][++c];
            if (c+1 < n) res[i++] = matrix[r][++c];
            else if (r+1 < m) res[i++] = matrix[++r][c];
            while (r+1 < m && c-1 >= 0) res[i++] = matrix[++r][--c];
            if (r+1 < m) res[i++] = matrix[++r][c];
            else if (c+1 < n) res[i++] = matrix[r][++c];
        }
        return res;
    }
}

linspiration
161 声望53 粉丝