码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode:matrix zigzag traversal

时间:2016-03-22 19:09:21      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

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

标签:

原文地址:http://www.cnblogs.com/zilanghuo/p/5307691.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!