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

Matrix Zigzag Traversal(LintCode)

时间:2015-12-06 21:04:11      阅读:621      评论:0      收藏:0      [点我收藏+]

标签:

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

 

Matrix Zigzag Traversal(LintCode)

标签:

原文地址:http://www.cnblogs.com/FJH1994/p/5024138.html

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