Matrix Zigzag Traversal (矩阵的之字型遍历 )

问题

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]

分析

整个之字形分为两个形态,一是向右上方,一是向左下方。
定义变量up为表示,true表示向上,false表示向下。‘定义r表示行号,c表示列号。
当为true的时候,r--,c++ ,当为false时,r++,c--。
现在考虑什么时候换方向。
当前已经在右边的时候需要换向同时是r++(右上角时包含);当前在上边时,需要换向同时c++;
当前在下边时需要换向同时c++(左下角时包含);当前在左边时,需要换向同时r++;

代码

public class Solution {
    /*
     * @param matrix: An array of integers
     * @return: An array of integers
     */
    public int[] printZMatrix(int[][] matrix) {
        // write your code here
        int r=matrix.length;
        int c=matrix[0].length;
        int[] res=new int[r*c];
        int index=0;
        int row=0;
        int col=0;
        boolean up=true;
        while(true){
            res[index] = matrix[row][col];
            index++;
            if (index == res.length) {
                break;
            }
            if (up) {
                if (col == c - 1) {
                    row++;
                    up = false;
                } else if (row == 0) {
                    col++;
                    up = false;
                } else {
                    row--;
                    col++;
                }
            } else {
                if (row == r - 1) {
                    col++;
                    up = true;
                } else if (col == 0) {
                    row++;
                    up = true;
                } else {
                    col--;
                    row++;
                }
            }
        }
        return res;
    }
};

你可能感兴趣的:(Matrix Zigzag Traversal (矩阵的之字型遍历 ))