Tuesday, May 3, 2016

[LintCode] 185 Matrix Zigzag Traversal 解题报告

Description
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]


思路
分成4个步骤循环做
1 往右走1步。不能走的话往下走1步。
2 往左下走走走。
3 往下走1步。不能走的话往右走1步。
4 往右上走走走。


Code
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[] result = new int[m * n];
        int index = 0;
        int x = 0;
        int y = 0;
        result[index++] = matrix[x][y];
        while (index < result.length) {
            if (y + 1 < n || x + 1 < m) {
                if (y + 1 < n) {
                    y++;
                }
                else {
                    x++;
                }
                result[index++] = matrix[x][y];
            }
            while (x + 1 < m && y - 1 >= 0) {
                result[index++] = matrix[++x][--y];
            }
            if (x + 1 < m || y + 1 < n) {
                if (x + 1 < m) {
                    x++;
                }
                else {
                    y++;
                }
                result[index++] = matrix[x][y];
            }
            while (x - 1 >= 0 && y + 1 < n) {
                result[index++] = matrix[--x][++y];
            }
        }
        return result;

    }
}