leetcode:matrix zigzag traversal

Posted 自朗活

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了leetcode:matrix zigzag traversal相关的知识,希望对你有一定的参考价值。

1、

  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]

2、不懂:

  

 /**
     * @param matrix: a matrix of integers
     * @return: an array of integers
     */ 
    public int[] printZMatrix(int[][] matrix) {
        // write your code here
            int x, y, dx, dy, count, m, n;
            x = y = 0;
            count = 1;
            dx = -1; dy = 1;
            m = matrix.length;
            n = matrix[0].length;
            int[] z = new int[m*n];
            z[0] = matrix[0][0];
            while (count<m*n) {
                if (x+dx>=0 && y+dy>=0 && x+dx<m && y+dy<n) {
                    x += dx; y += dy;
                }
                else
                    if (dx==-1 && dy ==1) {
                        if (y+1<n) ++y; else ++x;
                        dx = 1; dy = -1;
                    }
                    else {
                        if (x+1<m) ++x; else ++y;
                        dx = -1; dy = 1;
                    }
                z[count] = matrix[x][y]; ++count;
            }
            return z;
    }

 

以上是关于leetcode:matrix zigzag traversal的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode 103. Binary Tree Zigzag Level Order Traversal

#Leetcode# 103. Binary Tree Zigzag Level Order Traversal

LeetcodeBinary Tree Zigzag Level Order Traversal

LeetCode103. Binary Tree Zigzag Level Order Traversal 解题报告

一天一道LeetCode#103. Binary Tree Zigzag Level Order Traversal

[LeetCode]题解(python):103 Binary Tree Zigzag Level Order Traversal