zoukankan      html  css  js  c++  java
  • Matrix Zigzag Traversal(LintCode) .

    Matrix Zigzag Traversal

    Given a matrix of m x n elements (m rows, ncolumns), 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]

     1 public class Solution {
     2     /**
     3      * @param matrix: a matrix of integers
     4      * @return: an array of integers
     5      */ 
     6     public int[] printZMatrix(int[][] matrix) {
     7         int m = matrix.length;
     8         int n = matrix[0].length;
     9         int l = matrix.length*matrix[0].length;
    10         int[] result = new int[l];
    11         
    12         int d = -1;
    13         int x = 0;
    14         int y = 0;
    15         for(int i=0;i<l;i++) {
    16             result[i] = matrix[x][y];
    17             
    18             if(x+d < 0 && y < n-1 || x+d >= m && y >= 0) {
    19                 d = -d;
    20                 y++;
    21             }else {
    22                 if(y-d < 0 && x < m-1 || y-d >= n && x >= 0) {
    23                     d = -d;
    24                     x++;
    25                 }else {
    26                     x = x + d;
    27                     y = y - d;
    28                 }
    29             }
    30         }
    31         
    32         return result;
    33     }
    34 }
    View Code
  • 相关阅读:
    QtDBus编程详解
    QProcess详解
    python 爬虫 亚航 指定日期间的航线
    python 模块
    centos postgres 安装、远程连接
    python 爬虫 anyproxy
    python_scrapy_filespipe重写
    python_xpath
    常见问题汇总
    python_scrapy_log日志
  • 原文地址:https://www.cnblogs.com/FJH1994/p/5024138.html
Copyright © 2011-2022 走看看